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?
ModelChoiceField , which is a ChoiceField whose choices are a model QuerySet .
The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With