django Form的回顧--手動檔和自動擋
阿新 • • 發佈:2017-10-27
mod email request cts get choice 自動 ges field
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
手動檔: 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})
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)
#
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)
# 此種方式和手動擋效果一樣
part = ModelChoiceField(queryset=models.Role.objects.all())
def index(request):
form = UserInfoModelForm() return render(request,"index.html",{"from":form})
django Form的回顧--手動檔和自動擋