This article records the minimum practical demo of front-end and back-end integration.
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
]
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()
Generate migrations and apply them to create the database table:
python manage.py makemigrations # Detect changes in models
python manage.py migrate # Apply migrations
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)
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),
]
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
Create a Vue3 project with Vite and set up Axios and Ant Design Vue for the UI components:
Install Vue and other dependencies:
npm init vite@latest vue3-music --template vue
cd vue3-music
npm install
npm install axios ant-design-vue
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
}
})
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
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')
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)
}
}
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: