views:

71

answers:

3

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" maxlength="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.

+2  A: 

You can add attributes through the widget

 class DiaryEventForm(forms.Form):
  title = forms.CharField(max_length = 200, widget=forms.TextInput(attrs={'class': 'vTextField'}))
czarchaic
+1  A: 

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())
Dominic Rodger
A: 

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

Nike
I could, but I'd rather not include code in my templates for this (that comes under the "styling it myself" proviso in the question).
Dominic Rodger