使用一个插件django-crispy-forms可以很好的完成样式对接
1、安装库
pip install django-crispy-forms
2、注册apps
INSTALLED_APPS = [
...
'crispy_forms',
]
CRISPY_TEMPLATE_PACK = 'bootstrap4'
3、编写forms文件
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=130)
email = models.EmailField(blank=True)
job_title = models.CharField(max_length=30, blank=True)
bio = models.TextField(blank=True)
4、在模板中的用法
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<form method="post" novalidate>
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-success">Save person</button>
</form>
{% endblock %}
也可以针对单个元素做修改:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
**people/person_form.html**
{% block content %}
<form method="post" novalidate>
{% csrf_token %}
<div class="row">
<div class="col-6">
{{ form.name|as_crispy_field }}
</div>
<div class="col-6">
{{ form.email|as_crispy_field }}
</div>
</div>
{{ form.job_title|as_crispy_field }}
{{ form.bio|as_crispy_field }}
<button type="submit" class="btn btn-success">Save person</button>
</form>
{% endblock %}
其中关键点在于:{{ form|crispy }},对form做了转换即可。