Home  >  Article  >  Web Front-end  >  Technical details: Vue3+Django4 new project construction

Technical details: Vue3+Django4 new project construction

WBOY
WBOYOriginal
2023-09-08 08:51:271195browse

Technical details: Vue3+Django4 new project construction

Detailed technical explanation: Vue3 Django4 new project construction

Introduction:
Nowadays, the development model of front-end and back-end separation has become an essential skill for enterprise development. Vue and Django are very popular front-end and back-end frameworks. Their combination can greatly improve development efficiency and code quality. This article will introduce in detail how to build a new project, using Vue3 as the front-end framework and Django4 as the back-end framework, providing readers with code examples and detailed technical explanations.

1. Environment setup

  1. Front-end environment setup
    First, make sure you have installed the Node.js environment. Then, install Vue CLI 4.x using the following command:
npm install -g @vue/cli

Create a new Vue3 project using the following command:

vue create project-name

During the project initialization process, you need to select Vue3 as the version . After initialization is completed, enter the project directory and use the following command to run the project:

cd project-name
npm run serve
  1. Backend environment setup
    First, make sure you have installed the Python environment. It is recommended to use Python 3.9. Then, use the following Command to install Django 4.x:
pip install Django

Create a new Django project:

django-admin startproject project-name

Enter the project directory and use the following command to run the project:

cd project-name
python manage.py runserver

2. Front-end and back-end joint debugging

  1. Front-end configuration
    In the root directory of the Vue3 project, find the vue.config.js file. If it does not exist, create it manually. Add the following code to the file:
module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:8000', // 后端地址
        ws: true,
        changeOrigin: true
      }
    }
  }
}

This code configures the proxy server to forward the front-end API request to the back-end address.

  1. Backend configuration
    In the root directory of the Django project, find the settings.py file, modify ALLOWED_HOSTS and INSTALLED_APPS as follows:
ALLOWED_HOSTS = ['localhost', '127.0.0.1']

INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
]

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    ...
]

Then, in settings. Add the following code at the end of the py file:

CORS_ALLOW_ALL_ORIGINS = True

This code is configured to allow cross-domain requests.

3. Front-end and back-end interaction

  1. Front-end request
    In the Vue3 project, API requests are made by using the axios library. First, use the following command to install axios:
npm install axios

Then, in the component that needs to call the API, introduce axios and send the request:

import axios from 'axios'

axios.get('/api/example')
  .then(response => {
    console.log(response.data)
  })
  .catch(error => {
    console.error(error)
  })
  1. Backend response
    In Django, the Django Rest Framework (DRF) is used to build APIs. First, use the following command to install DRF:
pip install djangorestframework

Then, in the Django app directory, create a new file serializers.py and write the following code:

from rest_framework import serializers

class ExampleSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField(max_length=100)

Next, Create a new file views.py and write the following code:

from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import ExampleSerializer

@api_view(['GET'])
def example(request):
    data = [
        {'id': 1, 'name': 'example1'},
        {'id': 2, 'name': 'example2'},
    ]
    serializer = ExampleSerializer(data, many=True)
    return Response(serializer.data)

Finally, in the Django project directory, find the urls.py file and add the following code:

from django.urls import path
from . import views

urlpatterns = [
    path('example/', views.example),
]

In this way, the current end When sending a GET request to /api/example, the backend will return example data.

Conclusion:
Through the detailed explanation of this article, readers will understand how to use Vue3 as the front-end framework and Django4 as the back-end framework to build a new project. We explained the process of environment setup, front-end and back-end joint debugging, and front-end and back-end interaction, and provided corresponding code examples. I hope readers can master the basic usage of Vue and Django through this article and be able to apply them to actual projects.

The above is the detailed content of Technical details: Vue3+Django4 new project construction. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn