django Form的回顾--手动档和自动挡
from django.shortcuts import render
from django.forms import Form
from django.forms import fields
from django.forms import widgets
from django.forms.models import ModelChoiceField
from rbac import models
from 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")
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()
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})