1.urls.py --> 设置一个访问路径
# 导入三个模块文件 from django.contrib import admin from django.urls import re_path from app01 import views # 设置URL路径 urlpatterns = [ re_path('admin/', admin.site.urls), re_path('test/', views.test, name='test'), ]
2.test.html --> 创建一个html页面
<!-- 用之前先引入bootstrap的cdn资源 --> <div class="container"> <div class="row"> <form action="{% url 'test' %}" method="POST" novalidate="novalidate"> {% csrf_token %} {% for field in obj %} <hr> {{ field.label_tag }} <hr> {{ field }} {{ field.errors.0 }} {% endfor %} <hr> <input type="submit" value="提交"> </form> </div> </div>
3.models.py --> 设置models模型类
from django.db import models class UserType(models.Model): caption = models.CharField(max_length=32) class UserInfo(models.Model): username = models.CharField(max_length=32) email = models.EmailField() user_type = models.ForeignKey(to='UserType', to_field='id', on_delete=models.CASCADE)
4.forms.py --> 设置form组件验证
#!/usr/bin/env python # -*- coding:utf-8 -*- from django import forms from django.forms import widgets from django.forms import fields from app01.models import UserType class UserInfoForm(forms.Form): # username = models.CharField(max_length=32) <--> models username = fields.CharField(max_length=32) # email = models.EmailField() <-- models email = fields.EmailField() # user_type = models.ForeignKey(to='UserType',to_field='id') <--> models
# user_type字段用__init__实时更新,与数据库保持同步 user_type = fields.ChoiceField( ) # 下面的操作是让数据在网页上实时更新 def __init__(self, *args, **kwargs): super(UserInfoForm, self).__init__(*args, **kwargs) self.fields['user_type'].choices = UserType.objects.values_list('id', 'caption')
5.views.py --> 设置views视图函数
from django.shortcuts import render, HttpResponse, redirect from app01.forms import UserInfoForm def test(request): if request.method == 'GET': obj = UserInfoForm() return render(request, 'test.html', {'obj':obj}) else: obj = UserInfoForm(request.POST) return render(request, 'test.html', {'obj':obj})