Article directory
1. Django’s own backend management system
1. Create table
1.1 Open models.py under myapp and add the following content
from django.db import models
# Create your models here.
class Article(models.Model):
title = models.CharField('标题', max_length=256)
content = models.TextField('内容')
time = models.DateTimeField()
1.2 Next, you need to synchronize the database, which only requires two lines of commands.
python ./manage.py makemigrations
python ./manage.py migrate
At this time, you will find that there is a db.sqlite3 file in the root directory. When you open it, it will be garbled. Yes, this is the newly created table. Stored in the root directory as text. One more step is required. Open admin.py in the myapp directory, add the following content, and use the background management system to manage the newly created table.
from django.contrib import admin
from myapp.models import Article
# Register your models here.
class ArticleAdmin(admin.ModelAdmin):
list_display = ['title', 'content', 'time']
admin.site.register(Article, ArticleAdmin)
2. Backend management system
Django's backend management system is already very complete. All we need to do is create an account and log in. There is nothing else. We don't need to write anything ourselves.
2.1 Create an account
python manage.py createsuperuser
My username and password are both: admin
2.2 Running background
The admin URL already exists by default. You can access the Django backend by running the project directly.
python ./manage.py runserver
2.3 Login
Enter in browserhttp://127.0.0.1:8000/admin
Click 添加
us to add a set of data.
2. Template rendering
1. Render data directly to the page
Once the data is available, it must be displayed on the front end, which requires template rendering. First, you need to return the data together when rendering the template, and open the myapp directory.views.py
from django.shortcuts import render
from myapp.models import Article
# Create your views here.
def index(request):
article_list = Article.objects.all()
return render(request, 'index.html', {'article_list': article_list})
templates
The contents in the directory index.html
need to be modified as follows. The syntax of Django's janja2 rendering template is used here.
<html>
<head>
<title>test</title>
</head>
<body>
{% for article in article_list %}
<h1>{
{ article.title }}</h1>
<span>{
{ article.time }}</span>
<p>{
{ article.content }}</p>
{% endfor %}
</body>
</html>
Refresh browser
2. Pass data to js
Sometimes the data needs to be processed before being rendered to the page. In this case, the data must be given to js first. The specific operation method is almost the same as direct rendering.
index.html
Add this code here
<script>
let articleList = {
{ article_list | safe }};
console.log(articleList)
</script>
Modify the code of views
from django.shortcuts import render
from myapp.models import Article
import json
from django.core import serializers
from django.core.serializers.json import DjangoJSONEncoder
# Create your views here.
def index(request):
article_list = serializers.serialize('python', Article.objects.all())
return render(request, 'index.html', {'article_list': json.dumps(article_list, cls=DjangoJSONEncoder)})
3. Database
1. View the current database
Django comes withsqlite数据库
-
sqlite
Install plugin in vscode
-
Right click on the sqlite database and create a new query
-
Enter the query content, use
.help
View Help,.databases
view the database, use.tables
View Table, right-click and select Run Query to see the results.
select * from myapp_article
2. Create UserInfo data table
- Add the following code to model.py
class UserInfo(models.Model):
username = models.CharField('用户名', max_length=128)
password = models.CharField('密码', max_length=128)
class Meta:
verbose_name = '用户信息'
verbose_name_plural = '用户信息'
def __str__(self):
return self.username
- Execute the following command to create a database
python manage.py makemigrations
python manage.py migrate
- Use Django background for data management. Add the following code to the
directoryadmin.py
from django.contrib import admin
from myapp.models import UserInfo
admin.site.site_header = '任务管理系统'
class UserInfoAdmin(admin.ModelAdmin):
list_display = ('id', 'username', 'password',)
list_display_links = ('username',)
list_per_page = 50
admin.site.register(UserInfo, UserInfoAdmin)
3. Django rest framework configuration
- Install framework
pip install djangorestframework
# 暂时不装也可以
pip install markdown
# 用于数据筛选
pip install django-filter
Register the framework in settings
INSTALLED_APPS = [
'rest_framework',
]
- Serialization
Create serializer.py in the app directory and add the following code
from myapp.models import UserInfo
from rest_framework import serializers
class UserInfoSerializer(serializers.ModelSerializer):
class Meta:
model = UserInfo
fields = "__all__"
- Add a view.
Add the following code to view.py in the app directory:
from rest_framework.viewsets import ModelViewSet
from myapp.models import UserInfo
from myapp.serializer import UserInfoSerializer
from django_filters.rest_framework import DjangoFilterBackend
class UserInfoViewSet(ModelViewSet):
queryset = UserInfo.objects.all()
serializer_class = UserInfoSerializer
- Add route
Create the urls.py file in the app directory:
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from tadmin.views import UserInfoViewSet
router = DefaultRouter()
router.register('UserInfo', UserInfoViewSet, basename='UserInfo')
urlpatterns = [
]
urlpatterns += [
path('', include(router.urls)),
]
- Add the following code to the urls in the project root directory
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include('tadmin.urls')),
]
- Filter and search function configuration
Create filter.py file in the app root directory
from django_filters import FilterSet, filters
from myapp.models import UserInfo
class UserInfoFilter(FilterSet):
name = filters.CharFilter(field_name='username', lookup_expr='icontains')
class Meta:
model = UserInfo
fields = ('username',)
Modify the view file in the app directory:
from myapp.models import UserInfo
from myapp.serializer import UserInfoSerializer
from myapp.filter import UserInfoFilter
from django_filters.rest_framework import DjangoFilterBackend
# Create your views here.
def index(request):
article_list = serializers.serialize('python', Article.objects.all())
return render(request, 'index.html', {'article_list': json.dumps(article_list, cls=DjangoJSONEncoder)})
class UserInfoViewSet(ModelViewSet):
queryset = UserInfo.objects.all()
serializer_class = UserInfoSerializer
filter_class = UserInfoFilter
filter_fields = ['username',]
search_fields = ('username',)
Register django_filters in settings:
INSTALLED_APPS = [
'django_filters',
]
# REST_FRAMEWORK增加全局过滤配置
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': [
'django_filters.rest_framework.DjangoFilterBackend',
'rest_framework.filters.SearchFilter',
],
}
# 如果可以实现模糊查询,则以下语句可省略
FILTERS_DEFAULT_LOOKUP_EXPR = 'icontains'
- Pagination settings
Make the following changes in settings.py
# REST_FRAMEWORK增加全局过滤配置
REST_FRAMEWORK = {
# 设置分页
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}
- Automatically generate api documentation
pip install drf-yasg
Make the following modifications in the project folder setting.py
INSTALLED_APPS = [
'drf_yasg', # swagger
]
Make the following changes in app’s urls.py
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title="API平台",
default_version="v1",
description="接口文档",
terms_of_service="",
contact=openapi.Contact(email='[email protected]'),
license=openapi.License(name="BSD License"),
),
public=True
)
router = DefaultRouter()
router.register('UserInfo', UserInfoViewSet, basename='UserInfo')
urlpatterns = [
path('docs/', schema_view.with_ui('swagger',cache_timeout=0), name='schema-swagger-ui'),
]
Document Check whether the document is successful,http://127.0.0.1:8000/api/v1/docs/
4. Vue front-end construction
1. Create the front-end file in the root directory of the Django project
vue init webpack frontProject
2. Modify the code in src/components/HelloWorld.vue as follows
<template>
<div class="hello">
<h1>{
{ msg }}</h1>
<ul>
<li v-for="(user,index) in users" :key="index" style="display: block;">
{
{ index }}--{
{ user.username }}--{
{ user.password }}
</li>
</ul>
<form action="">
用户名:<input type="text" placeholder="user name" v-model="inputUser.username"><br>
密码:<input type="text" placeholder="user password" v-model="inputUser.password"><br>
<button type="submit" @click="userSubmit()">提交</button>
</form>
</div>
</template>
<script>
import { getUsers,postUser } from '../api/api.js';
export default {
name:'hellouser',
data () {
return {
msg:'Welcome to Your Vue.js App',
users:[
{username:'test1',password:'test1'},
{username:'test2',password:'test2'}
],
inputUser:{
"username":"",
"password":"",
}
}
},
methods:{
loadUsers(){},
userSubmit(){}
},
created: function(){
this.loadUsers()
}
}
</script>
5. Front-end and back-end joint debugging
1. Use django-cors-headers
modules to solve cross-domain problems
pip install django-cors-headers
Then add the module in project settings.py:
INSTALLED_APPS = [
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # 需注意与其他中间件顺序,这里放在最前面即可
...
]
# 支持跨域配置开始
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
The back-end part is configured. Next, you need to add the front-end logic.
2. Vue framework request
The Vue framework now generally uses the axios module for network requests. This method is used here. The following is the operation in the front-end project:
- First, install the axios module from the command line. If cnpm is not installed, use npm to install it:
npm install axios
- In order to facilitate the management of various logics of api requests, create an api directory in the src directory of the front-end project, and then create
api.js
andindex.js
files. The index.js file configures axios:
/src/api/index.js
import Vue from 'vue'
import Axios from 'axios'
const axiosInstance=Axios.create({
withCredentials:true
})
axiosInstance.interceptors.request.use((config)=>{
config.headers['X-Requested-With'] = 'XMLHttpRequest'
const regex = /.*csrftoken=([^;.]*).*$/
config.headers['X-CSRFToken'] = document.cookie.match(regex) === null ? null : document.cookie.match(regex)[1]
return config
})
axiosInstance.interceptors.response.use(
response=>{
return response
},
error=>{
return Promise.reject(error)
}
)
Vue.prototype.axios=axiosInstance
export default axiosInstance
api.js
The file is a request to the backend. You can see that getting the books list and adding a book each correspond to one request:
import axiosInstance from "./index";
const axios = axiosInstance
export const getUsers = () => {
return axios.get(`http://127.0.0.1:8000/api/v1/UserInfo/`)
}
export const postUser = (username, password) => {
return axios.post(`http://127.0.0.1:8000/api/v1/UserInfo/`, {
'username': username, 'password': password
})
}
- Then update the processing logic in Login.vue:
<template>
<div class="hello">
<h1>{
{ msg }}</h1>
<ul>
<li v-for="(user,index) in users" :key="index" style="display: block;">
{
{ index }}--{
{ user.username }}--{
{ user.password }}
</li>
</ul>
<form action="">
用户名:<input type="text" placeholder="user name" v-model="inputUser.username"><br>
密码:<input type="text" placeholder="user password" v-model="inputUser.password"><br>
<button type="submit" @click="userSubmit()">提交</button>
</form>
</div>
</template>
<script>
import { getUsers,postUser } from '../../../api/api.js';
export default {
name:'hellouser',
data () {
return {
msg:'Welcome to Your Vue.js App',
users:[
{username:'test1',password:'test1'},
{username:'test2',password:'test2'}
],
inputUser:{
"username":"",
"password":"",
}
}
},
methods:{
loadUsers(){
getUsers().then(response=>{
this.users=response.data.results
})
},
userSubmit(){
postUser(this.inputUser.username,this.inputUser.password).then(response=>{
console.log(response)
this.loadUsers()
})
}
},
created: function(){
this.loadUsers()
}
}
</script>
At this point, a simple Django+vue front-end and back-end separation project has been built, and the test adds data successfully.
As you can see, the data in the list is read from the backend, and the front-end submission database can also have corresponding operations, so the front-end and back-end are now connected.