删除外键选择字段中的所有元素 [英] Remove all the elements in a foreign key select field
问题描述
我有一个外键引用,该引用在客户端上显示为选择框,但已预先填充了值。我希望选择框在显示时为空,因为它将由Ajax调用填充。
I have a foreign key reference which shows up as a select box on the client but it is pre-populated with values. I want the select box to be empty when it shows because it will be populated by an Ajax call.
这是我的模型
class RecipeIngredient(models.Model):
recipe = models.ForeignKey(Recipe)
ingredient = models.ForeignKey(Ingredient)
serving_size = models.ForeignKey(ServingSize)
quantity = models.IntegerField()
order = models.IntegerField()
created = models.DateTimeField(auto_now_add = True)
updated = models.DateTimeField(auto_now = True)
这是我的模型表格
class RecipeIngredientForm(forms.ModelForm):
class Meta:
model = RecipeIngredient
fields = ('ingredient', 'quantity', 'serving_size')
widgets = {
'ingredient': forms.TextInput(attrs={'class' : 'recipe_ingredient'}),
'quantity': forms.TextInput(),
'serving_size' : forms.ChoiceField(choices=PLEASE_SELECT, widget=forms.Select()),
}
我希望 serving_size字段具有我指定的选择,而不是数据库中的任何数据。显然,我得到一个错误
I want the "serving_size" field to have the choices I specified and not any data from the database. Obviously, I get an error
AttributeError: 'ModelChoiceField' object has no attribute 'to_field_name'
有什么想法吗?
推荐答案
Don在字段
中不包含 serving_size
。而是自己添加:
Don't include serving_size
in fields
. Instead add it yourself:
class RecipeIngredientForm(forms.ModelForm):
serving_size = forms.ChoiceField(..)
尝试一下并告诉它是否可行。
Try this and tell, if it does the trick.
此外,我相信您不应该将 ChoiceField
放入 widgets
中,这不是小部件,
Furthermore, I believe you shouldn't put ChoiceField
into widgets
, this is not a widget, but a whole field.
EDIT
class RecipeIngredientForm(forms.ModelForm):
serving_size = forms.ChoiceField(choices=PLEASE_SELECT, widget=forms.Select())
class Meta:
serving_size = forms.ChoiceField(choices=PLEASE_SELECT, widget=forms.Select())
model = RecipeIngredient
fields = ('ingredient', 'quantity', 'serving_size')
widgets = {
'ingredient': forms.TextInput(attrs={'class' : 'recipe_ingredient'}),
'quantity': forms.TextInput(),
}
这篇关于删除外键选择字段中的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!