Django中Form的基本使用

from django import forms

from django.forms import fields

class UserInfo(forms.Form):

username = fields.CharField(required=True,error_messages={

'required':'username不能为空'

}) # 正则表达式

password = fields.CharField(required=True,error_messages={

'required':'password不能为空'

})

email = fields.EmailField(required=True,error_messages={

'required':'email不能为空',

'invalid':'email格式错误'

}) #不能为空

# 获取用户提交的数据 request.POST

# 数据和正则表达式进行验证

# 1.是否验证成功

# 2.成功:获取数据

# 3.失败:显示错误信息

def add_user(request):

if request.method == 'GET':

return render(request,'add_user.html')

else:

obj = UserInfo(request.POST)  # 定义一个form实例

# 获取是否验证成功 使用is_valid方法

if obj.is_valid():

print('验证通过',obj.cleaned_data)

models.UserInfo.objects.create(**obj.cleaned_data)

else:

print('错误信息',obj.errors)

总结:

Form验证:

a.Form类

b. obj = Form()

obj.username  <input .../>

c. obj = Form(request.POST)

obj.username  <input value=..../>

d. 验证

if obj.is_valid()

print('数据信息',obj.cleaned_data)

models.UserInfo.objects.create(**obj.cleaned_data)

else:

print('错误信息',obj.errors)

print('错误信息',obj.errors.usernaem[0])

return render(request,'add_user/',{'obj':obj})

===============>

Form 生成HTML标签

在index中添加  {{ obj.usernaem }}      自动生成html标签

from django.forms import widgets

widget=widgets.TextInput(attr={'class':'xxxx'})  #设置标签类型

Form 编辑

#============urls.py================

from app01 import views

urlpatterns = [

url(r'edit_user/(?P<uid>\d+)',views.edit_user),

]

#============views.py================

from django import forms

from django.forms import fields

from django.forms import widgets

class UserForm(forms.Form):

username = fields.CharField(

required=True,

error_messages = {'required':'username不能为空'},

widget = widgets.TextInput(attrs={'class':'form-control','placeholder':'用户名'}),

)

password = fields.CharField(

required = True,

error_messages = {'required':'password不能为空'},

widget = widgets.TextInput(attrs={'class':'form-control','placeholder':'密码'}),

)

email = fields.CharField(

required = True,

error_messages = {'required':'email不能为空'},

widget = widgets.TextInput(attrs={'class':'form-control','placeholder':'邮件'}),

)

from app01 import models

def edit_user(request,uid):

if request.method == 'GET':

user_obj = models.UserInfo.objects.filter(id=uid).first()

obj = UserForm(initial={'username':user_obj.username,'password':user_obj.password,'email':user_obj.email})

#或者

# user = models.UserInfo.objects.values('username','password','email').filter(id=uid).first()

# obj = UserForm(initial=user)

return render(request,'edit_user.html',{'obj':obj,'uid':uid})

elif request.method == 'POST':

obj = UserForm(request.POST)

if obj.is_valid():

models.UserInfo.objects.filter(id=uid).update(**obj.cleaned_data)

return redirect('/index1/')

else:

return render(request,'edit_user.html',{'obj':obj,'uid':uid})

Form中的select下拉框:

ut_id = fields.IntegerField(

required=True,

widget = widgets.Select(

attrs = {'class':'form-control'},

choices = [],

)

)

def __init__(self,*args,**kwargs)

super(UserForm,self).__init__(*args,**kwargs)

self.fields['ut_id'].widget.choices = models.UserType.values_list('id','usertype')

Form 小结:

1. 做提交数据的验证

2. 生成对应的HTML

3.

跨表操作时的数据库性能

select_related('Forkey')

上一篇:iOS TableView如何刷新指定的cell或section


下一篇:【python】抄写爬淘宝已买到的宝贝的代码