Django-Form表单(验证、定制、错误信息、Select)

Django form 流程

1、创建类,继承form.Form

2、页面根据类的对象自动创建html标签

3、提交,request.POST

封装到类的对象里,obj=UserInfo(request.POST)

4、用户输入是否合法

obj.is_valid()

5、全部合法,获取全部内容

obj.clean()

6、只有有不合法

obj.errors

首先关闭跨站请求

#'django.middleware.csrf.CsrfViewMiddleware',

有错误会阻止提交,并提示错误信息

成功提交,可以获取到提交的值

Form定制化

定制错误信息

mail = forms.EmailField(error_messages={'required':u'邮箱不能为空'})

定制错误规则

mobile = forms.CharField(validators=[mobile_validate,],

error_messages={'required':u'手机不能为空'})

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

from django.shortcuts import render from django import forms import re from django.core.exceptions import ValidationError def mobile_validate(value): mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$') if not mobile_re.match(value): raise ValidationError('手机号码格式错误') class UserInfo(forms.Form): email = forms.EmailField(error_messages={'required':u'邮箱不能为空'}) host = forms.CharField(error_messages={'required':u'主机不能为空'}) port = forms.CharField(error_messages={'required':u'端口不能为空'}) mobile = forms.CharField(validators=[mobile_validate,], #定义错误规则函数       error_messages={'required':u'手机不能为空'},       widget=forms.TextInput(attrs={'class':'form-control', #定义class       'placeholder':u'请输入手机号'}))      beizhu = forms.CharField(required=False, #备注允许为空       widget=forms.Textarea(attrs={'class':'form-control', #定义为多行输入框       'placeholder':u'请输入备注'})) user_type_choice = (   (0,u'普通用户'),        (1,u'高级用户'),       ) user_type = forms.IntegerField(widget=forms.widgets.Select(choices=user_type_choice,attrs={'class':'form-control'}))

保存用户输入内容

obj = AccountForm.LoginForm(request.POST)

Form表单验证以及错误信息

错误信息格式:

普通格式:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

from django.shortcuts import render,HttpResponse from web.forms import account as AccountForm def login(request): obj = AccountForm.LoginForm(request.POST) if request.method == 'POST': if obj.is_valid(): all_data = obj.clean() else: #用于Form表单提交        error = obj.errors #print error['username'][0] #print error['password'][0]        return render(request, 'account/login.html',{'obj':obj,'error':error}) return render(request, 'account/login.html',{'obj':obj})

创建一个simple_tag,使其输 error['username'][0]

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

{% load xx %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form action="/login/" method="post"> <p>{{ obj.username }} {% error_msg error.username %} </p> <p>{{ obj.password }} {% error_msg error.password %} </p> <input type="submit" value="提交"> </form>

JSON格式

1 2 3 4 5 6 7 8 9 10 11 12

def login(request): obj = AccountForm.LoginForm(request.POST) if request.method == 'POST': if obj.is_valid(): all_data = obj.clean() else: #用于Ajax error = obj.errors.as_json() #print error return HttpResponse(error) return render(request, 'account/login.html',{'obj':obj,'error':error}) return render(request, 'account/login.html',{'obj':obj})

+ View Code

Form生成select标签

静态select

动态select

当增加数据库数据时

不会更新,除非关闭程序,重新载入才会更新

解决方法:利用面向对象类的静态字段

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

from django import forms import json class ImportForm(forms.Form): #静态select HOST_TYPE_LIST = ( (0,'物理机'), (1,'虚拟机'), ) host_type = forms.IntegerField( widget=forms.Select(choices=HOST_TYPE_LIST) ) hostname = forms.CharField() #动态select # admin_dic = ((1,'yangmv'),(1,"bob"),) # w_obj = open('db_admin','w') # w_obj.write(json.dumps(admin_dic)) # w_obj.close() f_obj = open('db_admin','r') data = f_obj.read() data_tuple = json.loads(data) admin = forms.IntegerField( widget=forms.Select(choices=data_tuple) ) def __init__(self,*args,**kwargs): super(ImportForm,self).__init__(*args,**kwargs) tmp = open('db_admin') data = tmp.read() data_tuple = json.loads(data) self.fields['admin'].widget.choices = data_tuple

再次增加数据库数据,直接刷新页面即可读取到新数据

优化后代码

1 2 3 4 5 6 7 8 9 10 11

from django import forms import json class ImportForm(forms.Form): admin = forms.IntegerField(widget=forms.Select()) def __init__(self,*args,**kwargs): super(ImportForm,self).__init__(*args,**kwargs) tmp = open('db_admin') data = tmp.read() data_tuple = json.loads(data) self.fields['admin'].widget.choices = data_tuple

使用models获取select数据

(models操作,后面一偏文章会详细介绍)

1 2 3

class Select(models.Model): username = models.CharField(max_length=16) password = models.CharField(max_length=32)

1 2 3 4 5

<body> <form action="/home/"> <p>{{ obj.admin }}</p> </form> </body>

1 2 3

def home(request): obj = HomeForm.ImportForm() return render(request, 'home/home.html',{'obj':obj})

models.Select.objects.all().values_list('id','username')

https://www.cnblogs.com/yangmv/p/5327427.html

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券