【问题标题】:How add a * after required fields in django modelform?如何在 django modelform 中的必填字段后添加 *?
【发布时间】:2012-10-14 06:09:29
【问题描述】:

我有一个 django modelform,其中一些字段是必需的。我正在使用{{ form.as_p }},我没有单独访问这些字段。

那么如何在表单中为该必填字段添加星号 (*)?

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    最简单的方法是更改​​标签

    class Form(ModelForm):
        model = <model>
        labels = {
            "<field_name>": "<label>*",
        }
    

    或者您可以使用小部件为字段设置 id 并为该 id 设置标签:

    class Form(ModelForm):
        model = <model>
        widgets = {
            "<field_name>": "<widget_obj>(attrs={"id": "<id>"})*",
        }
    

    【讨论】:

      【解决方案2】:

      如果您不会单独访问字段(例如使用 {{ form.as_p }}),那么您可以将属性添加到您的 ModelForm:

      class FooForm(forms.ModelForm):
          required_css_class = 'required'
      

      这会将所有需要的字段定义为具有“必需”类

      然后您可以使用 CSS 添加星号:

      <style type="text/css">
          .required:after { content: '*'; }
      </style>
      

      【讨论】:

        猜你喜欢
        • 2013-04-18
        • 2012-11-06
        • 1970-01-01
        • 2015-11-10
        • 2011-08-08
        • 2019-04-04
        • 2012-01-26
        • 2023-03-09
        • 2018-07-25
        相关资源
        最近更新 更多