gpt4 book ai didi

css - Django:对于扩展另一个 ModelForm 的 ModelForm 不显示 CSS 类

转载 作者:行者123 更新时间:2023-11-28 11:43:15 27 4
gpt4 key购买 nike

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

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

这是我的代码:

模型.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)

表单.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)
)

最佳答案

找出问题所在:不正确地更新小部件字典。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"}),
})

关于css - Django:对于扩展另一个 ModelForm 的 ModelForm 不显示 CSS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20591022/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com