table of Contents
Form component dynamic binding data
First, an overview (with radio drop-down box, for example)
Generating a drop-down box Form component, typically drop-down box data acquired from the database. When adding or updating data in the database, we found that when you refresh the browser page, drop-down box data unchanged. You need to restart the django in practice it is not reasonable
# views.py
class Test2Form(forms.Form):
user = fields.ChoiceField(choices=models.UserInfo.objects.values_list('id','username'))
def test2(request):
obj = Test2Form()
return render(request,'test2.html',{"obj":obj})
# 数据库
id username email
1 小白 [email protected]
2 小花 [email protected]
# html
<span>姑娘:{{ obj.user }}</span>
Second, analysis
step1: When django start, class class will run, acquiring data in the database drop-down box
step2: add or modify data in the database, refresh the browser page. With the drop-down box data is not updated
step3: Because when you refresh the page, class of class properties do not regenerate again, it has been the beginning of the data retention
Third, a solution
Recommended Use: Rewrite __init __ () method in the class, when the page will refresh instance of an object, execute the method updating data
class Test2Form(forms.Form):
user = fields.ChoiceField()
# 在类中定义__init__()函数
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
# self.fields必须写在super()下面。因为super会将类属性全拷贝,self.filelds才能取到值
self.fields['user'].choices=models.UserInfo.objects.values_list('id','username')
def test2(request):
obj = Test2Form()
return render(request,'test2.html',{"obj":obj})
IV Solution two
Use django comes ModelChoiceField field generated drop-down box. It seems simpler than a method, but not recommended. Because of the need to write str method in the models. If another drop-down box to be displayed in the other field will not operated, models coupled with high
from django.forms.models import ModelChoiceField # 需要导入
class Test2Form(forms.Form):
user = ModelChoiceField(queryset=models.UserInfo.objects.all(),to_field_name='username')
'''
queryset, # 查询数据库中的数据
empty_label="---------", # 默认空显示内容
to_field_name=None, # HTML中option中value的值对应的字段
'''
在浏览器页面下拉框中显示 '表名 object' ,所以还需要修改model.py文件
# models.py
class UserInfo(models.Model):
username=models.CharField(max_length=32)
email=models.EmailField(max_length=32)
def __str__(self):
return self.username