如何使用Bootstrap CSS设置Django表单的样式? [英] How can I style django forms with bootstrap CSS?

查看:153
本文介绍了如何使用Bootstrap CSS设置Django表单的样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在django中编写了一个表单类,并在尝试输出它时发现它看起来并不漂亮.

I've written a form class in django, and while trying to output it, found that it is not beautiful to look at.

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 %}

我尝试根据建议

I attempted to style it as per the suggestions here. But the option attrs arent being accepted for Charfield.

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形式的bootstrap这样的CSS框架的正确方法是什么?

What is the proper way to use a css framework like bootstrap with django forms?

推荐答案

您需要的是小部件调整.

What you need is widget-tweaks.

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

It allows you to apply custom styles and CSS classes to django variables (which also includes form objects)

pip安装django-widget-tweaks

pip install django-widget-tweaks

然后将"widget-tweaks"添加到已安装的应用中.

Then add 'widget-tweaks' to your installed apps.

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

然后导入模板中的窗口小部件

Then import widget-tweaks in your template

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

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

Now suppose you want to apply class "abc" to a form element "email"

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

这会将"abc"类应用于该表单元素.
这是一种将样式应用于表单而不是弄乱后端代码的简便易行的方法

This will apply class "abc" to that form element.
This is a much easier and cleaner way to apply styles to forms rather than messing with the backend code

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

For more info or documentation on "django-widget-tweaks" look here :

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

这篇关于如何使用Bootstrap CSS设置Django表单的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆