views:

100

answers:

1

This problem is very strange and I'm hoping someone can help me. For the sake of argument, I have a Author model with ForeignKey relationship to the Book model. When I display an author, I would like to have a ChoiceField that ONLY displays the books associated with that author. As such, I override the AuthorForm.init() method and I create a List of choices (tuples) based upon a query that filters books based upon the author ID. The tuple is a composite of the book ID and the book name (i.e., (1, 'Moby Dick')). Those "choices" are then assigned to the ModelForm's choices attribute.

When the form renders in the template, the ChoiceField is properly displayed, listing only those books associated with that author.

This is where things get weird.

When I save the form, I receive a ValueError (Cannot assign "u'1'":Author.book" must be a Book instance). This error makes sense due to the FK relationship. However, if I add a "print" statement to the code, make no other changes, and then save the record, it works. The ValueError magically disappears. I've tried this a number of times, ensuring I haven't inadvertently made another change, and it works each time.

Does anyone know what's going on here?

+2  A: 

Not quite sure what you are doing wrong, but it is best to just modify the queryset:

class ClientForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.affiliate = kwargs.pop('affiliate')
        super(ClientForm, self).__init__(*args, **kwargs)
        self.fields["referral"].queryset = Referral.objects.filter(affiliate = self.affiliate)

    class Meta:
        model = Client

The above is straight out of one my projects and it works perfectly to only show the Referral objects related to the passed affiliate:

form = ClientForm(affiliate=request.affiliate)
Paolo Bergantino
Or provide a customized Manager.
S.Lott
Awesome suggestion! Worked perfectly. Thank you!
Huuuze