views:

30

answers:

1

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?

+1  A: 

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(),
        }
gruszczy
Thanks for the reply. If I don't include it in fields it does not show up on the page. I tried this fields = ('ingredient', 'quantity') serving_size = forms.ChoiceField()
iHeartDucks
I have added a full form. You have tried exactly this? I am pretty sure this should work.
gruszczy
Thanks it worked. If you don't mind can you please explain what we did? Did we just create a new field?
iHeartDucks
Yes, `ModelForm` allows you to not only derive fields from model, but also add your own fields to the form. Then you can use value from this field in save (in `self.cleaned_data['serving_size']`).
gruszczy