This is the sixth day of my participation in the More text Challenge. For details, see more text Challenge

This article is used to learn how to use Django +vue.js to achieve web front-end separation collaborative development. Take an example of an application that adds and removes database books.

Django framework official address: www.djangoproject.com/

The official address of vue.js framework is cn.vuejs.org/

First, build a Django project

1. Create project files and apps

Create django_vue

django-admin startproject django_vue
Copy the code

Go to django_vue and create the virtual environment django_vue_env

pip install virtualenv  # installation
virtualenv django_vue_env
Copy the code

Activate the virtual environment and install Django

source ./django_vue_env/bin/activate
Copy the code

Install Django and django-comms-headers (cross-domain), requests

Create a django app

python manage.py startapp app
Copy the code

Our directory should look like this, and the Appfront for the vue project will be created later.

Sqlite3 is the default database. If you need to change databases, you can configure databases in setting.py.

Add app to INSTALLED_APPS

INSTALLED_APPS = [
    'django.contrib.admin'.'django.contrib.auth'.'django.contrib.contenttypes'.'django.contrib.sessions'.'django.contrib.messages'.'django.contrib.staticfiles'.'app'
]

Copy the code

Add the database model with book_name and add_time to record the book name and add time.

from django.db import models



# Create your models here.
class Book(models.Model) :
    book_name = models.CharField(max_length=64)
    add_time = models.DateTimeField(auto_now_add=True)

    def __str__(self) :
        return self.book_name

Copy the code

Do database migration

python manage.py makemigrations app
python manage.py migrate
Copy the code

Add show_books and add_book apis to views.py, and return the request data through JsonResponse.

from django.shortcuts import render

# Create your views here.
# Need to import related modules
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.core import serializers
import requests
import json

from .models import Book

@require_http_methods(["GET"])
def add_book(request) :
    response = {}
    try:
        book = Book(book_name=request.GET.get('book_name'))
        book.save()
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)

@require_http_methods(["GET"])
def show_books(request) :
    response = {}
    try:
        books = Book.objects.filter()
        response['list']  = json.loads(serializers.serialize("json", books))
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)

Copy the code

Add API routing to urls.py in django_vue directory

from django.contrib import admin
from django.urls import path,include
import app.urls

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/',include(app.urls)),
]
Copy the code

Add view routing to urls.py in the app directory

from django.urls import path,re_path
# Import myApp views file
from . import views

urlpatterns = [
    re_path(r'add_book$', views.add_book),
    re_path(r'show_books$', views.show_books)
]

Copy the code

Restart the service and run the curl command to test the AVAILABILITY of the API. The following interfaces are normal:

Python manage. Py runserver then executes the curl http://127.0.0.1:8000/api/add_book? Book_name = mylife {" MSG ":" success ", "error_num: 0} {curl http://127.0.0.1:8000/api/show_books" list ": [{" model" : "App. The book", "pk" : 9, "fields" : {" book_name ":" mylife ", "add_time" : "the 2021-06-16 T14:44:49. 230 z"}}], "MSG" : "success", "error_num": 0}Copy the code

With the Django back end roughly built, next up is the VUE front end.


I. Build the VUE project

Install vUE. Initialize the command line tool vue- CLI

npm install -g vue-cli
Copy the code

Build the front-end project AppFront in the django_vue directory, which includes the WebPack tools.

vue-init webpack appfront
Copy the code

The AppFront directory is as follows

Install render element-UI, Vue-Resource

npm install element-ui
npm install vue-resource
Copy the code

Adjust SRC /main.js as follows

import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import VueResource from 'vue-resource'
import 'element-ui/lib/theme-chalk/index.css'

Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.use(VueResource)
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

Copy the code

Create a new home.vue in the SRC/Component directory with showBooks and addBook methods for API queries.

<template> <div class="home"> <el-row display="margin-top:10px"> <el-input V-model ="input" placeholder=" placeholder "> style="display:inline-table; width: 30%; float:left"></el-input> <el-button type="primary" @click="addBook()" style="float:left; margin: 2px;" > </ button> </ button> </ button> </ button> </ button> </ button> </ button> </ button> 100%" border> <el-table-column prop="id" label=" id" min-width="100"> <template scope="scope"> {{scope.row.pk}} </template> </el-table-column> <el-table-column prop="book_name" label=" min-width="100"> <template scope="scope"> {{ Scope.row.fields. Book_name}} </template> </el-table-column> <el-table-column prop="add_time" label=" add_time" min-width="100"> <template scope="scope"> {{ scope.row.fields.add_time }} </template> </el-table-column> </el-table> </el-row> </div> </template> <script> export default { name: 'home', data () { return { input: '', bookList: [], } }, mounted: function() { this.showBooks() }, methods: {{same () this. $HTTP. Get (' http://139.198.114.148:8000/api/add_book? book_name=' + this.input) .then((response) => { var res = JSON.parse(response.bodyText) if (res.error_num == 0) { This.showbooks ()} else {this.$message.error(' failed to add books, Try ') console.log(res[' MSG '])}})}, ShowBooks () {this. $HTTP. Get (' http://139.198.114.148:8000/api/show_books'). Then ((response) = > {var res = JSON.parse(response.bodyText) console.log(res) if (res.error_num == 0) { this.bookList = res['list'] } else { This. $message. Error (' query books failure) console. The log (res) [' MSG ']}})}}} < / script > <! -- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>Copy the code

We handle cross-domain issues with Django-comms-headers

INSTALLED_APPS = [
    'django.contrib.admin'.'django.contrib.auth'.'django.contrib.contenttypes'.'django.contrib.sessions'.'django.contrib.messages'.'django.contrib.staticfiles'.'app'.'corsheaders', // add app]Copy the code

Add corsheaders middleware. Middleware. CorsMiddleware

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware'.'django.contrib.sessions.middleware.SessionMiddleware'.'django.middleware.common.CommonMiddleware'.'django.middleware.csrf.CsrfViewMiddleware'.'corsheaders.middleware.CorsMiddleware'.'django.contrib.auth.middleware.AuthenticationMiddleware'.'django.contrib.messages.middleware.MessageMiddleware'.'django.middleware.clickjacking.XFrameOptionsMiddleware',]Copy the code

Configure cross-domain rules in setting.py

CORS_ALLOW_METHODS = (
    'DELETE'.'GET'.'OPTIONS'.'PATCH'.'POST'.'PUT'.'VIEW',
)
  
CORS_ALLOW_HEADERS = (
    'accept'.'accept-encoding'.'authorization'.'content-type'.'dnt'.'origin'.'user-agent'.'x-csrftoken'.'x-requested-with'.)Copy the code

NPM run dev Starts the node server

Package the front end to the dist directory via NPM Run build for subsequent Django links.


Django links to the front end

Adjust the route to urls.py in django_vue as follows

from django.contrib import admin
from django.urls import path,include
from django.views.generic importTemplateView // Import a generic viewimport app.urls

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/',include(app.urls)),
    path(' ',TemplateView.as_view(template_name="index.html")), // route to index.html]Copy the code

Add the static file address under setting.py

STATICFILES_DIRS = [(os.path.join(BASE_DIR,'appfront/dist/static')))Copy the code

Starting Django Services

python manage.py runserver
Copy the code

Visit our Django address, which is now linked to the front end


Reference: github.com/rogerlh/dja…

NEXT

  • Django-rest-framework creates restful apis
  • Django wsGI application

Feel free to point out any shortcomings in this article in the comments section.

Welcome to collect, like and ask questions. Keep an eye on top water cooler managers and sometimes do more than just boil hot water.