Django:CSS类没有为扩展另一个ModelForm的ModelForm显示

时间:2013-12-15 03:56:08

标签: css django django-forms django-widget django-models

我需要为表单字段分配一个CSS类,我指的是这个SO帖子: CSS styling in Django forms

但是,我无法使用扩展另一个ModelForm的ModelForm。 在下面的代码中,字段“title”和“base_title”应分别具有类“title”和“base_title”,但是,当您检查HTML时,它们都不会获得任何类。任何意见,将不胜感激。感谢。

这是我的代码:

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)
    )

1 个答案:

答案 0 :(得分:0)

发现问题所在:更新小部件字典不正确。 MyModelForm类应如下所示:

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"}),
})