David
David

Reputation: 69

Override maxlength input using Django form {{ form.as_p }}

In Django when I create a form from a model, in the template I use {{ form.as_p }} and for text inputs it creates the follow code:

<input id="id_var1" maxlength="8" name="var1" type="text">

Is it possible to override the maxlength value (in this case "8") with a variable I have in the views.py?

Upvotes: 1

Views: 2449

Answers (2)

Derek Kwok
Derek Kwok

Reputation: 13078

In your form fields, you can override the widget and add attrs parameter for custom HTML attributes.

class MyCustomForm(forms.ModelForm):

    var1 = forms.CharField(
        widget=forms.TextInput(attrs={
            # override/add custom HTML attributes in this dictionary
            'maxlength': '20',
        })
    )

    class Meta:
        model = MyCustomModel
        fields = ['var1', ...]

You can update the maxlength from a view like this:

form = MyCustomForm()
form.fields['var1'].widget.attrs['maxlength'] = '20'

Upvotes: 1

Alex Morozov
Alex Morozov

Reputation: 5993

The HTML maxlength parameter is handled by the browser, not by the Django's views. You should tweak your form or template to change the length of the field:

class YourForm(forms.Form):
    var_1 = forms.CharField(max_length=8)


def your_view(request, *args, **kwargs):
    max_length = int(request.GET['max_length'])
    form = YourForm(request.POST or None)
    form.fields['var_1'].max_length = max_length
    return render(request, 'template.html', dict(form=form))

Upvotes: 0

Related Questions