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)
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})
{% 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>
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})
<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="Ajax提交" onclick="SubmitAjax()"> </form> <script src="{{ STATIC_URL }}js/jquery-2.1.4.min.js"></script> <script> function SubmitAjax(){ $.ajax({ url:‘/login/‘, type:‘POST‘, data:{‘username‘:‘‘,‘password‘:‘‘}, success:function(arg){ console.log(arg) } }) } </script> </body>
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
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
class Select(models.Model): username = models.CharField(max_length=16) password = models.CharField(max_length=32)
<body> <form action="/home/"> <p>{{ obj.admin }}</p> </form> </body>
def home(request): obj = HomeForm.ImportForm() return render(request, ‘home/home.html‘,{‘obj‘:obj})
Django-Form表单(验证、定制、错误信息、Select)
原文:http://www.cnblogs.com/yangmv/p/5327427.html