【问题标题】:Applying bootsrap and custom css to {{form}} elements in django将引导程序和自定义 css 应用于 django 中的 {{form}} 元素
【发布时间】:2017-10-21 13:07:03
【问题描述】:

我正在尝试将 CSS 应用于我的 html 模板上的各个 {{form}} 字段。 我引用了这个已解决的问题:

CSS styling in Django forms`

使用答案,我创建了 forms.py 页面,如下所示:

from django import forms
from .models import ContactInfo


class ContactForm(forms.ModelForm):
# class meta brings in the fields from models
class Meta:
    model = ContactInfo

    # grab the fields from models ContactInfo class
    fields = ('Fullname')

    # specify which bootstrap class each html widget should take
    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        self.fields['Fullname'].widget.attrs.update({'class': 'form-control'})

使用 {{form}} 元素的html:

<div class="form-group">
  <label for="id_Fullname">Full Name:</label>
  {{form.Fullname}}
</div>

不使用 {{form}} 的工作 html:

<div class="form-group"> <label for="fullname">Full Name:</label> <input type="text" class="form-control" id="fullname"> </div>

如何让“标签”标签指向 {{form.Fullname}} 中的 id。我的猜测是它现在没有这样做,因此它不应用 css。我在 forms.py 的小部件中指定的那个或那个类没有按我想要的方式工作。

【问题讨论】:

    标签: django django-forms django-templates django-views


    【解决方案1】:
    <div class="form-group">
    {% for field in form %}
      <label for="id_Fullname" id="{{ field.name }}">Full Name:</label>
      {{ field }}
    {% endfor %}
    </div>
    

    试试这个

    【讨论】:

    • 不起作用。我在堆栈溢出时看到的这个问题的其他解决方案一定是遗漏了一些东西。将尝试从头开始再次执行此操作。
    • 解决了!我的 def init 函数位于 Class Meta 而不是 Class ContactForm 中。解决方案没有任何问题表明放置 def__init__ 时出错
    【解决方案2】:

    您可以使用fieldid_for_label 属性:

    使用此属性来呈现此字段的 ID。例如,如果您在模板中手动构建

    <div class="form-group">
      <label for="{{ form.Fullname.id_for_label }}">Full Name:</label>
      {{ form.Fullname }}
    </div>
    

    【讨论】:

    • 我尝试输入您的建议。同样的交易。不确定这是否意味着什么。我的 IDE(jetbrains/pycharm) 以红色突出显示 {{ form.Fullname.id_for_label }} 通过检查 xml 提及未解析的 id。我觉得 form.Fullname 不包含来自 ModelForm 类的自动创建的 id。将继续阅读您的链接。
    【解决方案3】:

    这是将 def init 函数放入 Class Meta: 而不是 Class ContactInfo 的错误。我没有意识到我的缩进不当。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-17
      • 2017-04-12
      • 2015-06-27
      • 1970-01-01
      • 2015-09-19
      • 1970-01-01
      • 2019-07-21
      • 2021-10-09
      相关资源
      最近更新 更多