0

I am using Django 4.1 and Bootstrap 5.

I think I'd like to mark required fields in a form as required, or maybe optional fields as optional, as suggested in this question.

Django/Bootstrap already styles fields as green/red after form submission, if a required field is missing, but my request is when the form is first rendered.

Could be with *s or with "(optional)" or whatever.

What's the best way to do it?

dfrankow
  • 20,191
  • 41
  • 152
  • 214

1 Answers1

0

A good option would be to override default fields attributes of a form. You can use for labels to add * or help_texts to add (required)for instance.

from django.utils.translation import gettext_lazy as _

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        labels = {
            'name': _('Writer *:'),
        }
        help_texts = {
            'name': _('(this field is required.)'),
        }

Niko
  • 3,012
  • 2
  • 8
  • 14