django Form的回顾"/>
django Form的回顾
from django.shortcuts import renderfrom django.forms import Form
from django.forms import fields
from django.forms import widgets
from django.forms.models import ModelChoiceField
from rbac import models
手动档: class UserInfoModelForm(Form): name = fields.CharField( required= True, error_messages={ "required": " 用户名不能为空 "})
email = fields.EmailField( required= True)
# 这样写不能时时更新 , 因为它是静态字段 , 只会在声明这个 class 的时候访问数据库一次
# part = fields.ChoiceField(choices=models.Role.objects.value_list("id","caption"))
part = fields.ChoiceField()
def __init__( self, *args, **kwargs):
super(). __init__(*args, **kwargs)
# 此种方式下 , 每次 new form 对象 , 都会执行数据库查询 , 数据时时更新
self.fields[ "part"].choices = models.Role.objects.value_list( "id", "caption") 自动档: class UserInfoModelForm(Form):
name = fields.CharField( required= True, error_messages={ "required": " 用户名不能为空 "})
email = fields.EmailField( required= True)
# 此种方式和手动挡效果一样 , 但是它会默认将 model_obj 中的 pk 作为 select 选择 option 的 value 值 , 不能配置 , 不推荐使用
part = ModelChoiceField( queryset=models.Role.objects.all())
def index(request):
form = UserInfoModelForm() return render(request,"index.html",{"from":form})
转载于:.html
更多推荐
django Form的回顾
发布评论