Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 493
Henri Avatar asked Apr 12 '10 15:04

Henri


People also ask

What is ModelChoiceField?

ModelChoiceField , which is a ChoiceField whose choices are a model QuerySet .

How do you make a field not required in Django?

The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).


1 Answers

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
like image 131
Mark Lavin Avatar answered Oct 01 '22 17:10

Mark Lavin