tags:

views:

519

answers:

2

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()
+1  A: 

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

oggy
Thanks! I don't understand everything django does behind the scenes yet, but that makes sense.
Komma
A: 

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. :)

Komma