django forms 解决新增的数据不更新的问题
场景描述:
在通过forms渲染页面form时,如果通过form.Select渲染一个单选项,而恰好此时的可选项来自数据库时,若数据库中有数据是可以正常运行项目的,但当初始化项目,初始化数据库,没有数据时就会报错。
解决方案:
- 使用lazy函数。(from django.utils.functional import lazy)
- 使用注意:
lazy(models.Breed.objects.all().values_list,list)()
- 具体代码:
from django.utils.functional import lazy
class PetInformation(forms.ModelForm):
name = CustomCharField(label="Name", help_text="Used to login, please remember your modification", )
gender = CustomCharField(label="Gender", widget=forms.Select(choices=(("W", "Women"), ("M", "Man"), ("U","Unknown"))))
weight = CustomCharField(label="Weight",)
birth_date = CustomCharField(label="Birth Date", widget=forms.DateInput())
color = CustomCharField(label="Color")
photo = CustomCharField(label="Photo",widget=forms.FileInput())
species = CustomCharField(label="Species", widget=forms.Select(choices=lazy(models.Species.objects.all().values_list,list)()))
breed = CustomCharField(label="Breed", widget=forms.Select(choices=lazy(models.Breed.objects.all().values_list,list)()))
class Meta:
model = models.Pet
exclude = ("join_date",)
如果涉及到动态数据,应使用ModelChoiceField
- 具体代码:
ql_belong = forms.ModelChoiceField(
label="订单服务器",
queryset=ql_models.QinglongManaer.objects.filter(is_main=1),
empty_label=None,
help_text="指定服务器",
)