Django: Why does my CharField not get given the class vTextField?
I have a form like this:
class DiaryEventForm(forms.Form):
title = forms.CharField(max_length = 200)
Which generates this HTML:
<input id="id_title" type="text" name="title" maxlength="200" />
This shows up as really narrow in the admin (where I've got a custom view using this form).
If I have a model defined like this:
class DiaryEvent(BaseModel):
title = models.CharField(max_length = 200)
I get this HTML:
<input id="id_title" type="text" class="vTextField" name="title" max开发者_如何学编程length="200" />
What's the most elegant way of getting the class vTextField
added to my form? That class seems to be the way normal text inputs are styled, so I'd like to use that, rather than styling it myself.
Whilst @czarchaic's answer worked (so +1), browsing the source yielded this solution, which I prefer:
from django.contrib.admin.widgets import AdminTextInputWidget
class DiaryEventForm(forms.Form):
title = forms.CharField(max_length = 200, widget = AdminTextInputWidget())
You can add attributes through the widget
class DiaryEventForm(forms.Form):
title = forms.CharField(max_length = 200, widget=forms.TextInput(attrs={'class': 'vTextField'}))
You can use this trick.
Put your fields into div with class:
<div class="vTextField">
<label>
{{ form.title }}
</label>
</div>
And here is corresponding css block:
.vTextField label{
your style here
}
In this case you don't have to specify style class in python
精彩评论