Issue
I am using Django and Python to create a custom admin interface for a model named ContentProgress. The ContentProgress model has a nullable ForeignKey field named custom_user_content.
However, when I try to save or edit a ContentProgress instance in the Django admin without providing a value for custom_user_content, I encounter an error stating "This field is required for Custom user Content."
# Admin class
class ContentProgressAdmin(admin.ModelAdmin, ExportCsvMixin):
list_display = ['user', 'lesson', 'in_percent', 'in_seconds', 'done', 'created_at', 'updated_at']
fields = ['user', 'lesson', 'in_percent', 'in_seconds', 'done', 'real_seconds_listened', 'custom_user_content']
search_fields = ['user__username', 'lesson__name', 'user__email']
list_filter = ['done', ('custom_user_content', RelatedDropdownFilter), ('user__company', RelatedDropdownFilter)]
autocomplete_fields = ['user', 'lesson', 'custom_user_content']
actions = ['export_as_csv']
admin.site.register(ContentProgress, ContentProgressAdmin)
# Model
class ContentProgress(Progress):
lesson = models.ForeignKey(MediaFile, on_delete=models.CASCADE)
custom_user_content = models.ForeignKey(CustomUserContent, null=True, on_delete=models.CASCADE)
def __str__(self):
return f'{self.lesson.name} - {int(self.in_percent * 100)}%'
Despite setting null=True for the custom_user_content field, I still face validation issues in the Django admin.
How can I properly handle nullable ForeignKey fields in the admin interface to avoid this error?
Solution
From the doc
Note that this is different than
null
.null
is purely database-related, whereas blank is validation-related. If a field hasblank=True
, form validation will allow entry of an empty value. If a field hasblank=False
, the field will be required.
So, you should set blank=True
in your models as well in this case to avoid the validation errors.
class ContentProgress(Progress):
lesson = models.ForeignKey(MediaFile, on_delete=models.CASCADE)
custom_user_content = models.ForeignKey(
CustomUserContent,
null=True,
blank=True,
on_delete=models.CASCADE
)
def __str__(self):
return f'{self.lesson.name} - {int(self.in_percent * 100)}%'
See this SO post to get the in-depth idea of null
vs blank
Answered By - JPG
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.