I'm having trouble assigning a CSS class to a form field, even after following the guidance in this Stack Overflow post: CSS styling in Django forms
Specifically, I am facing issues when working with a ModelForm that extends another ModelForm. In the code snippet below, the fields "title" and "base_title" are supposed to have classes "title" and "base_title" respectively. However, upon checking the HTML output, neither of them actually receives any class. Any suggestions or advice on how to fix this would be greatly appreciated. Thank you.
Below is the relevant code:
models.py:
from django.db import models
class BaseModel(models.Model):
base_title = models.CharField(max_length=50, blank=True)
class MyModel(BaseModel):
title = models.CharField(max_length=50, blank=True)
forms.py:
from django.forms import ModelForm, TextInput
from testproj.models import MyModel
class BaseModelForm(ModelForm):
class Meta:
model = MyModel
fields = ("base_title",)
widgets = {
"base_title" : TextInput(attrs={"class" : "base_title"}),
}
class MyModelForm(BaseModelForm):
class Meta(BaseModelForm.Meta):
model = MyModel
fields = BaseModelForm.Meta.fields + ("title",)
widgets = BaseModelForm.Meta.widgets.update({
"title" : TextInput(attrs={"class" : "title"}),
})
views.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
from testproj.forms import MyModelForm
def index(request):
form = MyModelForm()
return render_to_response(
"testproj/index.html",
{
"form": form,
},
context_instance=RequestContext(request)
)