首页 > 解决方案 > Django:复选框未显示在 HTML 中

问题描述

此表格有多种选择。但是复选框不会显示在 HTML 中!我正在使用 Materialize CSS。请帮忙。

表格.py:

FAVORITE_COLORS_CHOICES = (
('blue', 'Blue'),
('green', 'Green'),
('black', 'Black'),
)

class StudentForm(forms.ModelForm):
    favorite_colors = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=FAVORITE_COLORS_CHOICES,
    )

表单.html:

<div class="container">
<form>

{{ form.as_p }}

<input type='submit' value='Save' />

</form>

浏览器中的 HTML 页面:

浏览器中的 HTML 页面:

从浏览器查看源代码:

<form>

    <p><label for="id_student_name">Student name:</label> <input type="text" name="student_name" maxlength="200" required id="id_student_name"></p>
<p><label for="id_present">Present:</label> <input type="checkbox" name="present" required id="id_present"></p>
<p><label>Favorite colors:</label> <ul id="id_favorite_colors">
    <li><label for="id_favorite_colors_0"><input type="checkbox" 
name="favorite_colors" value="blue" id="id_favorite_colors_0">
 Blue</label>

</li>
    <li><label for="id_favorite_colors_1"><input type="checkbox" 
name="favorite_colors" value="green" id="id_favorite_colors_1">
 Green</label>

</li>
    <li><label for="id_favorite_colors_2"><input type="checkbox" 
name="favorite_colors" value="black" id="id_favorite_colors_2">
 Black</label>

</li>
</ul></p>

    <input type='submit' value='Save' />

    </form>

更新:

 {% for field in form %}
        <p>
            <input type="checkbox" id=field />
        <label for=field>Hello</label>
        </p>
    {% endfor %}

标签: pythonhtmldjango

解决方案


我遇到过同样的问题。如果您使用的是材质前端,您可以通过以下方式渲染它:

{% load material_form %}
...
<form method="get">
    {% form form=form %}{% endform %}
    <input type="submit" class="btn btn-default" value='send' />
</form>

推荐阅读