django Form的回顾--手动档和自动挡
Posted jec1999
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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})
以上是关于django Form的回顾--手动档和自动挡的主要内容,如果未能解决你的问题,请参考以下文章