Вопрос

I need to assign a CSS class to a form field and I was referring to this SO post: CSS styling in Django forms

However, I could not get it to work with ModelForm that extends another ModelForm. In the code below the fields "title" and "base_title" are expected to have classes "title" and "base_title" respectively, however, neither of them gets any class when you check HTML. Any advice would be appreciated. Thanks.

Here is my 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)
    )
Это было полезно?

Решение

Found out what the problem was: incorrect updating the widget dictionary. The class MyModelForm should look as following:

class MyModelForm(BaseModelForm):
    class Meta(BaseModelForm.Meta):
        model = MyModel
        fields = BaseModelForm.Meta.fields + ("title",)
        widgets = BaseModelForm.Meta.widgets
        widgets.update({
        "title" : TextInput(attrs={"class" : "title"}),
})
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top