Komma
Komma

Reputation: 23

Django ModelForms: Trying to save a form using a foreign key ID

I'm trying to create a new Topic and the category id is dynamically determined in javascript on the client side. The problem i'm having is I pass the category id and I want to lookup the correct category object, but using a model form, it checks if the category is an instance of Category before I can assign it and save it.

--model.py--

class Topic(models.Model):
    category = models.ForeignKey(Category)

--form.py--

class TopicForm(ModelForm):
    category = forms.IntegerField(widget=forms.HiddenInput())

    class Meta:
        model = Topic
        fields = ('category')

--view.py--

form = TopicForm(request.POST)

if form.is_valid():
    form.save(commit=False) # throws exception category is not a Category instance
    form.category = Category.objects.get(pk=form.cleaned_data.get('category'))
    form.save()

Upvotes: 1

Views: 2204

Answers (2)

Komma
Komma

Reputation: 23

Following Oggy's suggestion, I changed it to a ModelChoiceField and now Django does all the magic behind the scenes.

category = forms.ModelChoiceField(Category.objects.all(), widget=forms.HiddenInput())

Now I hope the queryset doesn't get evaluated, since it's not necessary and there are 90,000 records. :)

Upvotes: 1

oggy
oggy

Reputation: 3571

Use a ModelChoiceField instead of the IntegerField in your form. See the built-in fields reference

Upvotes: 3

Related Questions