zoukankan      html  css  js  c++  java
  • django forms lazy来自数据库的数据

    场景描述:

    在通过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",)
    
    • 如果涉及到instace的验证,应该使用ModelChoiceField
    • 具体代码:
    species = forms.ModelChoiceField(queryset=models.Species.objects.all(),label="Species",widget=forms.Select(attrs={"class":"form-control form-control-sm bg-light"}))
        breed = forms.ModelChoiceField(queryset=models.Breed.objects.all(),label="Species",widget=forms.Select(attrs={"class":"form-control form-control-sm bg-light"}))
    
  • 相关阅读:
    字符串练习题
    js
    百度商桥--提供网站与用户之间交流平台
    git从本地上传到码云
    命名单词
    swiper 点击切换,拖动切换后继续自动轮播
    ionic4创建新项目
    两个年月日相减,获取年数和年数及半年数
    微信小程序点击跳转出现背景
    列表数据进行左浮动造成页面空白一块,排版错位问题
  • 原文地址:https://www.cnblogs.com/lisicn/p/15567970.html
Copyright © 2011-2022 走看看