开发者

Remove all the elements in a foreign key select field

开发者 https://www.devze.com 2023-01-09 04:20 出处:网络
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

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.

This is my model

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)

and this is my model form

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

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'

Any ideas?


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.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号