标签:ice span lse use hid widget strong asc play
Django中为用户定义了一个django.forms库,这个库可以方便的进行form类的数据显示及数据验证,省去了很多用户的代码。django.forms库用起来也方便,只需要在HTML文件中需要增加<form>tag时,定义相应的Form类就可以。在以下的实例中,我们最终的页面上只有一个<form> tag, 所以我们只需要定义一个Form类即可。Django 社区的惯例是把Form类单独放在一个forms.py文件中,我们最好也遵循这个规则。创建disk\forms.py文件,并写入
新建一个项目
from django.db import models class Depart(models.Model): caption = models.CharField(max_length=32) def __str__(self): return self.caption class Role(models.Model): title = models.CharField(max_length=32) def __str__(self): return self.title class User(models.Model): name = models.CharField(verbose_name=‘姓名‘,max_length=32) depart = models.ForeignKey(verbose_name=‘部门‘,to=‘Depart‘,on_delete=models.CASCADE) gender_choices = ( (1,‘男‘), (2,‘女‘), ) gender = models.IntegerField(verbose_name=‘性别‘,choices=gender_choices,default=1) roles = models.ManyToManyField(verbose_name=‘角色‘,to=‘Role‘)
1 from django.shortcuts import render,redirect 2 from app01 import models 3 4 def user_list(request): 5 user_queryset = models.User.objects.all() 6 return render(request,‘user_list.html‘,{‘user_queryset‘:user_queryset}) 7 8 from django import forms 9 class UserForm(forms.ModelForm): 10 class Meta: 11 model = models.User 12 fields = ‘__all__‘ 13 # fields = ‘__all__‘ 14 # widgets = { 15 # ‘name‘:forms.TextInput(attrs={‘class‘:‘form-control‘}), 16 # ‘depart‘:forms.Select(attrs={‘class‘:‘form-control‘}), 17 # ‘gender‘:forms.Select(attrs={‘class‘:‘form-control‘}), 18 # ‘roles‘:forms.SelectMultiple(attrs={‘class‘:‘form-control‘}), 19 # } 20 error_messages = { 21 ‘name‘:{ 22 ‘required‘:‘用户名不能为空‘ 23 } 24 } 25 26 27 def user_add(request): 28 if request.method == "GET": 29 form = UserForm() 30 else: 31 form = UserForm(request.POST) 32 if form.is_valid(): 33 print(‘通过验证‘) 34 form.save() 35 return redirect(‘/user/list/‘) 36 return render(request, ‘user_add.html‘, {‘form‘: form})
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^user/list/$‘,views.user_list), url(r‘^user/add/$‘,views.user_add), ]
标签:ice span lse use hid widget strong asc play
原文地址:https://www.cnblogs.com/haowen980/p/9526868.html