abidibo.net

Required class attribute in django ModelForm

django tips

Days ago' I was developing a front-end form in order to give users the opportunity to subscribe to a newsletter. I used the django ModelForm class because I didn't need nothing special except from hiding some model fields.

But I run into a problem, the compulsory fileds where handled properly in the sense that the form submission returned an error if such fields weren't filled, but there wasn't any attribute assigned to the label element in order to style it different from non-compulsory fields.

Nothing special here, nor complicated, but it costs me a while to find the reason for this, so I'll share it with you. The simple solution is to add a line ( required_css_class = 'required' ) into the form class:

class subscriptionform(forms.ModelForm):
  required_css_class = 'required'
  class meta:
    model = subscription
    exclude = ['categories','code','notes',]

This way if you renders the form as a table the tr element which contains the compulsory field gets a required class.

That's it, nothing special, just a tip.

Subscribe to abidibo.net!

If you want to stay up to date with new contents published on this blog, then just enter your email address, and you will receive blog updates! You can set you preferences and decide to receive emails only when articles are posted regarding a precise topic.

I promise, you'll never receive spam or advertising of any kind from this subscription, just content updates.

* indicates required

abidibo.net topics

Comments are welcome!

blog comments powered by Disqus

Your Smartwatch Loves Tasker!

Your Smartwatch Loves Tasker!

Now available for purchase!

Featured