djangoformswidgetsuffix

Django form widget - Add suffix while keeping the NumberInput


I have a form input on body height. I would like to put 'cm' after the height number (e.g. 183cm instead of just selecting 183) but keep it as a NumberInput.

Is it possible to add the suffix in the widget?

I have the following form.py:

from django import forms
from .models import Account

class RegistrationForm(forms.ModelForm):
    body_height = forms.NumberInput(attrs={'min':120,'max':230,'step':1, 'required':False,})


    class Meta:
        model = Account
        fields = ['body_height','otherfields']


    def __init__(self, *args, **kwargs):
        self.fields['body_height'].widget.attrs['placeholder'] = 'Your height (centimeters)'

Solution

  • from django.utils.safestring import mark_safe
    
    
    class NumberInputWithSuffix(forms.NumberInput):
        def render(self, name, value, attrs=None):
            return super().render(name, value, attrs) + mark_safe(' cm')
    
    
    class RegistrationForm(forms.ModelForm):
        body_height = forms.IntegerField(
            widget=NumberInputWithSuffix(
                attrs={'min': 120, 'max': 230, 'step': 1, 'required': False, }
            ),
            input_formats=['%d'], format='%d cm'
        )
    
        # your code ...
    

    You can extend the default NumberInput's render method and change the default Html.