Hero Image of content
Django and Vue3 Frontend-Backend Development Record: Music List CRUD

This article records the minimum practical demo of front-end and back-end integration.

Django and Vue3 Frontend-Backend Development Record: Music List CRUD

Part 1: Django Setup

1.1 Project Initialization

Create a new Django project and app:

django-admin startproject music_project  # Create project
python manage.py startapp music         # Create app

Register the app in the settings.py:

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "music",  # Register music app
    "corsheaders",  # For CORS handling
]
1.2 Model Registration

Define your model in music/models.py:

from django.db import models

class Music(models.Model):
    title = models.CharField(max_length=250)
    artist = models.CharField(max_length=250)
    duration = models.FloatField()
    last_day_played = models.DateField()
1.3 Migrations

Generate migrations and apply them to create the database table:

python manage.py makemigrations  # Detect changes in models
python manage.py migrate         # Apply migrations
1.4 Adding Initial Data

Create a custom management command to add data from a JSON file:

from datetime import datetime
import json
from django.core.management.base import BaseCommand
from django.utils.timezone import make_aware
from music.models import Music
from django.conf import settings

class Command(BaseCommand):
    help = 'Create tracks from JSON file'

    def handle(self, *args, **kwargs):
        datafile = settings.BASE_DIR / 'data' / 'tracks.json'
        assert datafile.exists()

        with open(datafile, 'r') as f:
            data = json.load(f)

        DATE_FMT = "%Y-%m-%d %H:%M:%S"
        for track in data:
            track_date = datetime.strptime(track['last_play'], DATE_FMT)
            track['last_play'] = make_aware(track_date)

        musics = [Music(**track) for track in data]
        Music.objects.bulk_create(musics)
1.5 NinjaAPI Setup

NinjaAPI, which is more streamlined than Django REST Framework (DRF), is used for API development. Here’s how to set up the API in api.py:

from ninja import NinjaAPI
from music.models import Music
from music.scheme import MusicSchema, NotFoundSchema
from typing import List

api = NinjaAPI()

@api.get("/musics", response=List[MusicSchema])
def get_musics(request):
    return Music.objects.all()

@api.get("/musics/{id}", response={200: List[MusicSchema], 404: NotFoundSchema})
def get_music(request, id: int):
    try:
        return [Music.objects.get(pk=id)]
    except Music.DoesNotExist:
        return 404, {"message": "Not Found"}

Add these API routes to the urls.py:

from django.urls import path
from music.api import api

urlpatterns = [
    path("admin/", admin.site.urls),
    path("api/", api.urls),
]
1.6 CORS Handling

Install the django-cors-headers package to handle CORS issues:

pip install django-cors-headers

In settings.py:

INSTALLED_APPS = [
    "corsheaders",  # Add this to INSTALLED_APPS
]

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",  # Add this middleware
]

CORS_ALLOW_ALL_ORIGINS = True  # Allow all origins for development

Part 2: Vue3 Setup

2.1 Project Initialization

Create a Vue3 project with Vite and set up Axios and Ant Design Vue for the UI components:

  1. Install Vue and other dependencies:

    npm init vite@latest vue3-music --template vue
    cd vue3-music
    npm install
    npm install axios ant-design-vue
    
2.2 Vite Configuration

Configure the Vite server in vite.config.ts:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  server: {
    host: '0.0.0.0',
    port: 5173,
    strictPort: true
  }
})
2.3 Axios Request Setup

Set up Axios for API calls in request.ts:

import axios from 'axios'

const service = axios.create({
  baseURL: 'http://127.0.0.1:8000/api',
  timeout: 5000
})

service.interceptors.request.use(config => {
  if (localStorage.getItem('token')) {
    config.headers.token = localStorage.getItem('token') || ''
  }
  return config
})

service.interceptors.response.use(
  response => response.status === 200 ? response : Promise.reject(new Error(response.statusText)),
  error => Promise.reject(error)
)

export default service
2.4 Vue Setup

Integrate Ant Design Vue and Axios in main.ts:

import { createApp } from 'vue'
import App from './App.vue'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/antd.css'
import axios from './api/request'

const app = createApp(App)
app.use(Antd)
app.mount('#app')
2.5 CRUD Operations

Make CRUD operations for adding, editing, and deleting music in the frontend. Here’s an example for adding music:

import { ref } from 'vue'
import axios from './api/request'

const musics = ref([])

const addMusic = async (music) => {
  try {
    const response = await axios.post('/add_music', music)
    musics.value.push(response.data)
  } catch (error) {
    console.error('Error adding music:', error)
  }
}

Summary:

This project involves creating a simple music list CRUD app with Django and Vue3. Django serves as the backend, utilizing NinjaAPI for cleaner, faster development compared to Django REST Framework (DRF). Vue3 is used for the frontend, leveraging Axios for API requests and Ant Design Vue for UI components.

Key steps include:

  • Setting up Django with models, migrations, and APIs.
  • Using NinjaAPI for simpler API handling.
  • Configuring Vue3 to interact with the Django backend.