Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django 删除外键选择字段中的所有元素_Django_Django Models - Fatal编程技术网

Django 删除外键选择字段中的所有元素

Django 删除外键选择字段中的所有元素,django,django-models,Django,Django Models,我有一个外键引用,它在客户端上显示为一个选择框,但它预先填充了值。我希望选择框在显示时为空,因为它将由Ajax调用填充 这是我的模型 class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe) ingredient = models.ForeignKey(Ingredient) serving_size = models.ForeignKey(ServingSize) quant

我有一个外键引用,它在客户端上显示为一个选择框,但它预先填充了值。我希望选择框在显示时为空,因为它将由Ajax调用填充

这是我的模型

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()),
        }
我希望“服务大小”字段具有我指定的选项,而不是数据库中的任何数据。显然,我犯了一个错误

AttributeError: 'ModelChoiceField' object has no attribute 'to_field_name'

有什么想法吗?

不要在
字段中包含
服务大小
。而是自己添加:

class RecipeIngredientForm(forms.ModelForm):
    serving_size = forms.ChoiceField(..)
试试这个,告诉我,如果它真的奏效了

此外,我认为您不应该将
ChoiceField
放入
widgets
,这不是一个widget,而是一个完整的字段

编辑

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(),
        }

谢谢你的回复。如果我没有将其包含在字段中,它将不会显示在页面上。我尝试了这个字段=('Component','quantity')提供的大小=表单。ChoiceField()我添加了一个完整的表单。你试过这个吗?我很确定这应该行得通。谢谢,行得通。如果你不介意的话,你能解释一下我们做了什么吗?我们刚刚创建了一个新字段吗?是的,
ModelForm
不仅允许您从模型派生字段,还允许您将自己的字段添加到表单中。然后您可以在保存中使用此字段中的值(在
self.cleaned_data['service_size']
中)。