Django Multiplechoicefield不在页面上显示

时间:2019-04-10 17:17:55

标签: python html django

我正在尝试获取一个包含名称和月份的表格,并将返回具有该名称和月份的学生(出勤系统)。我正在为表单使用MultipleChoiceField,但它不会在浏览器中呈现。我也在使用Materialize CSS。如何解决此问题?我也在手动呈现表单字段。

forms.py:

class attendenceFinder(forms.Form):
    months = ((1, 'JAN'),
             (2, 'FEB'),
             (3, 'MAR'),
             (4, 'APR'),
             (5, 'MAY'),
             (6, 'JUN'),
             (7, 'JUL'),
             (8, 'AUG'),
             (9, 'SEP'),
             (10, 'OCT'),
             (11, 'NOV'),
             (12, 'DEC')
    )    

    name = forms.CharField()
    month = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=months)

attendence.html:

<form action="/get_attendence/", method="post">
<div class="container">
        {{ form.non_field_errors }}
    <div class="fieldWrapper">
        {{ form.name.errors }}
        <label for="{{ form.name.id_for_label }}">Name</label>
        {{ form.name }}
    </div>
    <div class="fieldWrapper">
        {{ form.month.errors }}
        <label for="{{ form.month.id_for_label }}">{{form.month}}
            <span>{{ form.month.label }}</span>
        </label>
    </div>
    <button class="waves-effect waves-light btn-large lime accent-2 black-text" type="submit" name="action">Submit
    <i class="material-icons right">send</i>
    </div>
</form>

页面来源:

   <div class="fieldWrapper">

        <select name="month" required id="id_month" multiple>
  <option value="1">JAN</option>

  <option value="2">FEB</option>

  <option value="3">MAR</option>

  <option value="4">APR</option>

  <option value="5">MAY</option>

  <option value="6">JUN</option>

  <option value="7">JUL</option>

  <option value="8">AUG</option>

  <option value="9">SEP</option>

  <option value="10">OCT</option>

  <option value="11">NOV</option>

  <option value="12">DEC</option>

</select>
        <span>Month</span>

    </div>

浏览器中的表单:

enter image description here

名称字段呈现良好,但“月份”多项选择却不正确。

2 个答案:

答案 0 :(得分:1)

Django材料对于使用Materializecss的表单呈现非常有帮助。这是项目https://github.com/viewflow/django-material的链接。

答案 1 :(得分:0)

材料化CSS希望看到带有class =“ browser-default”的标签。但是,Django表单不会添加该类。因此,必须在form.py中传递以下内容:

class attendenceFinder(forms.Form):
    months = ((1, 'JAN'),
              (2, 'FEB'),
              (3, 'MAR'),
              (4, 'APR'),
              (5, 'MAY'),
              (6, 'JUN'),
              (7, 'JUL'),
              (8, 'AUG'),
              (9, 'SEP'),
              (10, 'OCT'),
              (11, 'NOV'),
              (12, 'DEC')
    )
 month = forms.MultipleChoiceField(choices=months, widget=forms.Select(
            choices=months,
            attrs={'class': 'browser-default'}))

所有功劳归于此链接:

https://github.com/Dogfalo/materialize/issues/4904