如何使用Bootstrap CSS设置Django表单的样式?

时间:2018-07-31 10:36:14

标签: django django-forms bootstrap-4

我用django编写了一个表单类,并试图输出它时,发现它看起来并不漂亮。

class AddAppointmentForm(forms.Form):
    docchoices = []
    for doc in doctor.objects.all():
        docst = [doc.docid, doc.name]
        docchoices.append(docst)
    # CHOICES = [('select1', 'select 1'),
    #            ('select2', 'select 2')]
    name = forms.CharField(label='Name', max_length=100)
    gender = forms.ChoiceField(
        required=True,
        widget=forms.RadioSelect,
        choices=[('male', 'Male'), ('female', 'Female')]
    )
    age = forms.IntegerField(max_value=100,min_value=1, required=True)
    phone = forms.CharField(label='Phone', max_length=14, required=True)
    email = forms.CharField(label='Email', max_length=25, required=False)
    address = forms.CharField(label='Address', max_length=60, required=False)
    city = forms.CharField(label='City', max_length=20, required=False)
    doctors = forms.ChoiceField(
        required=True,
        widget=forms.Select,
        choices=docchoices,
    )

{# Load the tag library #} {% extends "appointments/base.html" %} {% block title %}Create appointment{% endblock %} {% block content %}
<div class="container">
    <form class="needs-validation" novalidate="" action="/appointments/appointmentcreated" method="post">
        {% csrf_token %}
        <div class="row">
            <div class="col-md-12 mb-6">
                <label for="Name">Name</label> {{ form.name }}
            </div>
        </div>
        <div class="row py-2 ">
            <div class="input-group col-md-6 mb-3">
                <span class="input-group-addon">Age</span> {{ form.age }}
            </div>
            <div class="input-group col-md-6 mb-3">
                <span class="input-group-addon">Gender</span> {{ form.gender }}
            </div>
        </div>
        <div class="row py-2 ">
            <div class="mb-3">
                <label for="email">Phone
                <span class="text-muted">(Required)</span>
            </label> {{ form.phone }}
            </div>
        </div>
        <div class="row py-2 ">
            <div class="mb-3">
                <label for="email">Email
                <span class="text-muted">(Optional)</span>
</label> {{ form.email }}
            </div>
        </div>

        <div class="mb-3">
            <label for="address">Address</label> {{ form.address }}
        </div>

        <div class="row">
            <div class="col-md-12 mb-6">
                <label for="city">City</label> {{ form.city }}
            </div>
        </div>
        <div class="row">
            <div class="col-md-12 mb-6">
                <label for="sel_doctor">Select Doctor</label> {{ form.doctors }}
            </div>
        </div>

        <div class="row">
            <div class="col-md-2 mb-1">
                <button class="btn btn-primary btn-block" type="submit">Create appointment</button>
            </div>
        </div>
    </form>
</div>
{% endblock %}

Without bootstrap

我尝试按照建议here设置样式。但是Charfield接受了attrs arent选项。

name = forms.CharField(label='Name', max_length=100, attrs={
                       'class': 'form-control'})


File "/home/joel/myappointments/appointments/forms.py", line 7, in <module>
    class AddAppointmentForm(forms.Form):
File "/home/joel/myappointments/appointments/forms.py", line 15, in AddAppointmentForm
    'class': 'form-control'})
File "/home/joel/.local/lib/python3.6/site-packages/django/forms/fields.py", line 214, in __init__
    super().__init__(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'attrs'

将Django表单之类的css框架与bootstrap一起使用的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

您需要的是窗口小部件调整。

它允许您将自定义样式和CSS类应用于django变量(还包括表单对象)

  

pip安装django-widget-tweaks

然后将“ widget-tweaks”添加到已安装的应用中。

INSTALLED_APPS = [
...
'widget_tweaks',
...
]

然后导入窗口小部件-在模板中进行调整

{% load static %}
{% load widget_tweaks %}
...

现在假设您要将类“ abc”应用于表单元素“电子邮件”

{{ form.email|add_class:"abc" }}

这会将“ abc”类应用于该表单元素。
这是一种将样式应用于表单而不是弄乱后端代码的简便,简洁的方法

有关“ django-widget-tweaks”的更多信息或文档,请点击此处:

https://github.com/jazzband/django-widget-tweaks