0

I have a regular form with the basic template:

<form method="post" action="">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="submit">
</form>

The form consists of three integer fields defined in forms.py

class InitForm(forms.Form):
    row_1 = forms.IntegerField(initial=1, min_value=1)
    row_2 = forms.IntegerField(initial=1, min_value=1)
    row_3 = forms.IntegerField(initial=1, min_value=1)

The maximum value is set at runtime using input from the user. I have added it to the context by using

get_context_data()...

in the form view class, but how do I set the maximum input value for the three integer fields in the template? I can already output the maximum value in the template by

{{ maximum_value }}

I am just having trouble adding it to the form fields. For reference I need the maximum value on all the fields

2 Answers 2

1

Try the following in your template.

<input type="number" name="test" min="1" max="{{ maximum_value }}">

Refer: https://www.w3schools.com/tags/att_input_max.asp

Sign up to request clarification or add additional context in comments.

1 Comment

can this be done by looping through all the form fields in the template?
1

I have managed to successfully implement this in django 2.2.7 by using the following:

In my class based FormView I set the maximum value, then update the form in the context:

    def get_form_kwargs(self):
        kwargs = super(InitView, self).get_form_kwargs()
        if self.csv_maximum_row:
            kwargs[self.csv_row_max_kwarg] = self.csv_maximum_row
        return kwargs

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['form'].update_max()
        return context

as all the fields in the form require the maximum value the update max function in forms.py is:

    def update_max(self):
        for field in self.fields:
            self.fields[field].widget.attrs.update({'max': self.csv_maximum_row})

when rendered the maximum value for the form in the template is the value set in the FormView class. This means you can still use basic templating:

<form method="post" action="">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="submit">
</form>

without having to dive into the HTML of the fields individually.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.