开发者

Dynamically customize django form widgets

Specifically I want to add an error class if the field is i开发者_如何学JAVAnvalid. So it would render out like this:

<input type="text" name="email" class="error" />

The example blow seems hacky and I have not seen any other examples of how to achieve this.

http://jj.isgeek.net/2010/10/27/add-error-class-to-widgets-with-errors-in-django-forms/

Is it possible to globally override the default widget templates? I would like to have classes like required (or html5 required attr) if the field is required so it can be validated with JavaScript first. With the new html5 input types coming along I'd like to be able to use type="number" for integer fields for instance.

I have read these docs which were not much help. http://docs.djangoproject.com/en/dev/ref/forms/widgets/#customizing-widget-instances

Edit Apparently there is a required_css_class and error_css_class for forms. However, I am using modelForms and this doesn't seem to work.


Unfortunately, there is no simple way beyond the hack you have already identified using the standard django.

Is it possible to globally override the default widget templates?

How to solve this is being debated by the django developers.

For now, the solution that should appeal to you the most should be using an external package by a django core developer Carl: django-form-utils, that allows you to override templates, include arbitrary classes and include fieldsets.

And, include the following in your forms.py

from form_utils.forms import BetterModelForm as ModelForm
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜