【问题标题】:Override django form's clean method to change the ModelChoiceField queryset覆盖 django 表单的 clean 方法以更改 ModelChoiceField 查询集
【发布时间】:2011-08-17 00:56:35
【问题描述】:

我有这个模型:

class PetAttribute(models.Model):
    species = models.ForeignKey(PetSpecies, related_name = "pets")
    pet_category = models.ForeignKey(PetCategory, related_name = "pets", blank=True, null=True)
    pet_type = models.ForeignKey(PetType, related_name = "pets", blank=True, null=True)
    additional_fields= models.ManyToManyField( AdditionalField, null= True, blank=True )

现在我想在 select (pet_category, pet_type) 中添加一个附加选项,即

("0","其他")

在这些查询集中。我试过了,但是表单给我一个错误

错误:选择一个有效的选项。该选择不是可用的选择之一。

here 是它的一个解决方案,但我想通过 ModelChoiceField 来做到这一点

有什么建议吗?

谢谢:)

【问题讨论】:

    标签: django-forms overriding


    【解决方案1】:

    虽然有可能,但您确定这是您想要做的吗?您正在告诉一个验证模型对象选择的字段接受无效答案。

    创建“其他”PetType 和 PetCategory 对象或使用 empty_label 作为“其他”可能比强制 ModelChoiceField 接受任意值更有意义。

    然后要查找选择了“其他”的对象,查询无,

    pattrs_w_other_pet_type = PetAttribute.object.filter(pet_type=None)
    

    【讨论】:

    • 感谢您的回复......先生有什么办法,我可以覆盖干净的方法并允许这个“其他”选项。基本上,当用户从选项中选择其他选项时,我想为他填写一个文本字段,该文本字段将动态显示给用户,在选择此“其他”选项后,此文本字段将是强制性填写...所以在这种情况下请帮助我..
    猜你喜欢
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    相关资源
    最近更新 更多