重写 django 表单的 clean 方法来更改 ModelChoiceField 查询集
我有这个模型:
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","其他")
在这些查询集中。我已经尝试过,但表格给了我一个错误
错误:选择一个有效的选项。该选择不是可用的选择之一。
这里是它的一个解决方案,但我想通过 ModelChoiceField 执行此操作
有什么建议吗?
谢谢 :)
I have this model:
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 )
Now i want to add an additional option in select (pet_category, pet_type), which is
("0","Other")
in queryset of these. I have tried but form give me an error
Error: Select a valid choice. That choice is not one of the available choices.
here is a one solution of it, but i want to do this by ModelChoiceField
Any suggestion?
Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
虽然这是可能的,但您确定这是您想要做的吗?您正在告诉验证模型对象选择的字段接受无效答案。
创建“其他”PetType 和 PetCategory 对象或使用
empty_label
作为“其他”可能比强制 ModelChoiceField 接受任意值更有意义。然后要查找选择了“其他”的对象,查询“无”,
While it is possible, are you sure this is what you want to do? You are telling a field that validates choices to the model objects to accept a non-valid answer.
Creating an "other" PetType and PetCategory object or using
empty_label
as "other" might make more sense than forcing the ModelChoiceField to accept arbitrary values.Then to find objects with "other" selected, query for None,