开发者

is a ModelChoiceField always required?

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开发者_JAVA百科 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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜