Search code examples
pythondjangoforms

How to add custom title for form fields in Django?


I created this simple form:

class FormsProject(forms.Form):
    fullname = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control mb-3', 'placeholder': 'Aisf Payenda'}))
    Django = forms.BooleanField(widget=forms.CheckboxInput())
    Flask = forms.BooleanField(widget=forms.CheckboxInput())
    gender = forms.ChoiceField(
        widget=forms.RadioSelect(), choices=SELECT_GENDER)
    comments = forms.CharField(widget=forms.Textarea(attrs={
        'class': 'form-control mb-2',
        'rows': 4,

    }), help_text='Write here your message!')

and it looks like

enter image description here

How do I add a title asking something like "Your favorite frameworks: " before those checkbox, let me illustrate it:

enter image description here

Help me add that title before checkbox, thanks


Solution

  • You can rendering fields manually, for example:

    <div class="form-group">
      <div class="input-group">
        <label>{{ form.fullname.label }}</label>
        {{ form.fullname }}
        {{ form.fullname.errors }}
      </div>
    </div>
    
    <div class="form-group">
      <h2>Your favorite frameworks</h2>
    </div>
    
    <div class="form-group">
      <div class="input-group">
        <label>{{ form.Django.label }}</label>
        {{ form.Django }}
        {{ form.Django.errors }}
      </div>
    </div>
    
    <div class="form-group">
      <div class="input-group">
        <label>{{ form.Flask.label }}</label>
        {{ form.Flask }}
        {{ form.Flask.errors }}
      </div>
    </div>
    

    See this docs for more https://docs.djangoproject.com/en/dev/topics/forms/#rendering-fields-manually