How to render form field with information that it is required

前端 未结 5 941
孤街浪徒
孤街浪徒 2020-12-06 04:35

Is there any clever way to make django forms render field with asterisks after fields that are required? Or to provide some other clever for to mark required fields? I would

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-06 04:54

    As of Django 1.2, if your form has an attribute named required_css_class, it will be added to BoundField.css_classes for required fields. You can then use CSS to style the required parts of the form as desired. A typical use case:

    # views.py
    class MyForm(django.forms.Form):
        required_css_class = 'required'
        …
    

    /* CSS */
    th.required { font-weight: bold; }
    

    
    
      {{form.name.label_tag}}
      {{form.name.errors}}{{form.name}}
    
    

    If you use Form.as_table(), Form.as_ul, and Form.as_p, they do this automatically, adding the class to ,

  • , and

    , respectively.

提交回复
热议问题