0

I have this form:

class ZeroIntegrationConfigForm(ModelForm):
class Meta:
    model = ZeroIntegrationEntry
    fields = ['tab_title', 'description', 'country', 'operations',
              'locale', 'company_name']

That I generate with:

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

But I can't figure out / find how to assign html class to each input element generated, is the only way to do this writing the html manually for each element?

2
  • read about widget_tweaks and use {% render_field field_name class+='your_class' %} Commented Jul 10, 2020 at 7:04
  • or you can also apply classes directly inside ModelForm using widgets Commented Jul 10, 2020 at 7:06

1 Answer 1

1

you can add init to your ModelForm like this:

class ZeroIntegrationConfigForm(forms.Form):
# Your declared form fields here
...

    def __init__(self, *args, **kwargs):
        super(ZeroIntegrationConfigForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'your-class'

if you want to set a different class for each tag you can add ' if ' in the ' for '

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

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.