views:

70

answers:

1

I have a model

class Article(models.Model):
    .
    .
    language = models.ForeignKey(Language, help_text="Select the article's language")
    parent_article = models.ForeignKey('self', null=True, blank=True)

If an article is an original article then 'parent_article=None'. If an article is a translation then 'parent_article' <> None.

So I created:

class ArticleAdminForm(forms.ModelForm):
    .
    .
    parent_article = forms.ModelChoiceField(queryset=AyurvedicArticle.objects.filter(parent_article=None), help_text="Select the parent article (if any)")

    class Meta:
        Article

class ArticleAdmin(admin.ModelAdmin):
    form = ArticleAdminForm
    .
    .

Now when I apply all this it seems to work fine, but when I don't select a 'parent article' I get an error message in Admin stating "This field is required" even though the model says: "null=True, Blank=True".

When I don't use the customized form, i.e. leaven out the statement

class ArticleAdmin(admin.ModelAdmin):
#    form = ArticleAdminForm
    .
    .

then everything work, except now I get to many choices. In the documentation of "ModelChoicesField" you can read a phrase "Note that if a ModelChoiceField is required..." implying a ModelChoiceField does not need to be required.

Any idea how to deal with this?

+3  A: 

If you are going to override the form you need to set the field as not required in the ArticleAdminForm.

class ArticleAdminForm(forms.ModelForm):
    .
    .
    parent_article = forms.ModelChoiceField(
        queryset=AyurvedicArticle.objects.filter(parent_article=None),
        required=False,
        help_text="Select the parent article (if any)"
    )

    class Meta:
        Article
Mark Lavin
Worth emphasizing the point: if you override a field, you override *all* its attributes, including whether or not it is required.
Daniel Roseman
Thanks very much for the explanation. Actually I knew it had something to do with the 'required=False' but I had the syntax wrong.
Henri