Question

How to display the label for the field DateField?

My model has the following field:

drum_period_1 = models.DateField(
    'qwerty',
    blank=True,
    null=True,
)

forms.py:

class DrumDataForm(forms.ModelForm):
    drum_period_1 = forms.DateField(
        widget=forms.TextInput(attrs={
            'class':'datepicker',
        }),
        required=False,
    )

    class Meta:
        model = UserProfile
        fields = (
            'drum_period_1', 
        )

template.html:

<label class="label">{{ form.drum_period_1.label }}</label>

The displayed label is 'drum_period_1', but 'qwerty' had to be shown.

Was it helpful?

Solution

According to the documentation:

The default label for a Field is generated from the field name by converting all underscores to spaces and upper-casing the first letter. Specify label if that default behavior doesn’t result in an adequate label.

Pass the label argument to the DateField constructor:

drum_period_1 = forms.DateField(
    widget=forms.TextInput(attrs={
        'class':'datepicker',
    }),
    required=False,
    label = "qwerty"
) 

Or, rename drum_period_1 to qwerty:

class DrumDataForm(forms.ModelForm):
    qwerty = forms.DateField(
        widget=forms.TextInput(attrs={
            'class':'datepicker',
        }),
        required=False,
    )

    class Meta:
        model = UserProfile
        fields = (
            'qwerty', 
        )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top