Kenneth Reitz
Kenneth Reitz

Reputation: 8856

Is there any way to add a class attribute to an input tag generated by django.models?

I can't figure it out for the life of me. I don't think it's possible. Something so simple shouldn't be hard at all. Anyone?

Upvotes: 1

Views: 774

Answers (4)

kball
kball

Reputation: 4971

I don't think any of these is particularly what the asker was looking for and now a few years after the question was posted this can be done much more intuitively. I think the asker wants the ModelForm field to render the input tag with a class attribute which you set in your view.

If so, the answer is here:

How do I set default widget attributes for a Django ModelForm?

Indeed, maybe this was the case even way back in 09, in which case the other answers should be downvoted. But I wasn't working with Django back then so I'll leave that to others.

Upvotes: 0

Jonny Buchanan
Jonny Buchanan

Reputation: 62813

django-html provides a templatetag which allows you to add extra attributes in the template, like so:

{% field form.fieldname class="myclass" %}

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 600026

You just need to override the relevant field in your form class, and add your attribute to the widget. This is described clearly in the documentation.

Upvotes: 1

michael
michael

Reputation: 1767

Not sure what you're referring to. Do you mean an HTML <input> tag generated by django.forms? If so, just specify a custom widget, using the attrs attribute in the constructor. See docs.

Upvotes: 5

Related Questions