I’ve got the following model field:
category = models.ForeignKey("QuestionCategory", on_delete=models.CASCADE, null=False, blank=False )
Is it proper behaviour of Django, that when rendering it in an HTML form, on the select list there are all options (all categories) as well as “empty option”, represented by -----------
(as on the image here)?:
Still, if selecting that empty option and trying to save, there is a validation error, so that I need to select one of the element from the list…
3
Is it proper behaviour of django, that rendering it in html form.
Yes, it will still use ---
, but reject it when you submit the form. It might also be better than just pick already a value, since that “hints” to the user that they probably better pick that value. It would also mean certain users could overloop the field.
If you still want to automatically select the first item, you could probably work with:
def default_category():
return QuestionCategory.objects.first()
class Question(models.Model):
category = models.ForeignKey(
'QuestionCategory',
on_delete=models.CASCADE,
null=False,
blank=False,
default=default_category,
)
But it is probably better to let the user pick a value explicitly than hoping the first item is the category.