Search code examples
pythondjangodjango-formstooltipdjango-crispy-forms

How to implement tooltip with django form


I have a model form based on this model:

class MyModel(TimeStampedModel):
    MY_CHOICES = [tuple([x,x]) for x in range(1,8)]
    p1 = models.IntegerField("P1", default='1', help_text='text1')
    p2 = models.IntegerField("P2", default='1', help_text='text2')
    Parent = models.ForeignKey(ParentModel, on_delete=models.CASCADE)

The form itself looks like:

class MyModelForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.helper = FormHelper(self)
        self.helper.form_id = 'id-CaseForm'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'
        self.helper.form_tag = False
        self.helper.help_text_inline = False
        self.helper.form_show_labels = False
        self.helper.layout = Layout(
            Row(Field(PrependedText('p1', ‘field_label1’,  wrapper_class='col-12 col-lg-6 pe-0 stretchprepend'))),
          Row(Field(PrependedText('p2’, ‘field_label2’,  wrapper_class='col-12 col-lg-6 pe-0 stretchprepend’))))

        CHOICES = [tuple([x,x]) for x in range(1,8)]
        p1 = IntegerField( label='field_label1', widget=Select(choices=CHOICES))
        p2 = IntegerField( label='field_label2’, widget=Select(choices=CHOICES))

    class Meta:
        model = MyModel
        fields = ['p1', 'p2’,]

And this is displayed as a crispy form in the template:

{% crispy MyModelForm  %}

I want the user to see some help text when they hover over the fields. This help text could be the help_text from the model, or I am happy to put it somewhere else (although it should go in either the model or the form, not in the template). Any help appreciated.


Solution

  • The default html tooltip is available by defining title attribute on the Field. Help texts and other attributes of fields can be accessed from self.base_fields

    For your case it will be:

    self.helper.layout = Layout(
         Row(Field(
              PrependedText('p1', ‘field_label1’,wrapper_class='col-12 col-lg-6 pe-0 stretchprepend'),
    
              title=self.base_fields['p1'].help_text   # tooltip content
            ),
         )),
    

    If you're using Bootstrap - nicer tooltip is available by:

    Bootstrap 5

    Field('field_name',
          title=self.base_fields['field_name'].help_text,
          data_bs_toggle='tooltip', 
          data_bs_placement='top')
    

    And in the template:

    <script>
      $('[data-bs-toggle="tooltip"]').tooltip()
    </script>
    

    Bootstrap 4

    Field('field_name',
          title=self.base_fields['field_name'].help_text,
          data_toggle='tooltip', 
          data_placement='top')
    

    And in the template:

    <script>
      $('[data-toggle="tooltip"]').tooltip()
    </script>