Django: Can I have two labels for a field?

491 views Asked by At

I have a django form and I need to display unit of measurement.

For example, for a form field I have label and value. I also need to have another 'label' for unit measurement.

E.g. Weight [Textbox] Kg

How can I add Kg in a form in forms.py? I'm using crispy forms module to render my forms.

This is an example from forms.py .

class WeightForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(LifeEventsForm, self).__init__(*args, **kwargs)
        self.helper=FormHelper(self)
        self.helper.layout = Layout(
             'weight',

             FormActions(
                Submit('submit', "Save changes"),
                Submit('cancel',"Cancel")
            ),
        )
        self.helper.form_tag = False
        self.helper.form_show_labels = True

class Meta:
    model = myWeight

My models.py looks like:

class myWeight(models.Model):
    id = models.IntegerField()
    weight = models.IntegerField(null=True,blank=True)

    def __str__(self):
        return str(self.id)
1

There are 1 answers

0
madzohan On

Maybe not best idea, but pretty straightforward:

You can override from crispy_forms.layout import Field with custom template

class DoubleLabeledField(Field):
    template = "your_custom_field.html"

copypaste to your_custom_field.html everything from .../site-packages/crispy_forms/templates/bootstrap3/field.html (replace bootstrap3 if another template package) and put some info near every entrance of {{ field.label|safe }}

Then in your form should be:

self.helper.layout = Layout(
             DoubleLabeledField('weight'),

             FormActions(
                Submit('submit', "Save changes"),
                Submit('cancel',"Cancel")
            ),
        )