django的form组件加样式
时间: 2023-05-29 20:04:29 浏览: 97
可以使用Bootstrap样式来美化Django Form组件。
首先,在Django项目中安装Bootstrap,可以通过pip命令安装:
```
pip install django-bootstrap4
```
然后,在Django项目的settings.py文件中添加以下内容:
```
INSTALLED_APPS = [
# ...
'bootstrap4',
# ...
]
# 设置Bootstrap版本
BOOTSTRAP4 = {
'include_jquery': True,
'jquery_url': '//cdn.bootcss.com/jquery/3.3.1/jquery.min.js',
'base_url': '//cdn.bootcss.com/bootstrap/4.1.3/',
}
```
接着,在Django Form组件中使用Bootstrap样式:
```python
from django import forms
from django.utils.translation import gettext_lazy as _
class ContactForm(forms.Form):
name = forms.CharField(
label=_("Your Name"),
max_length=100,
widget=forms.TextInput(attrs={'class': 'form-control'}),
)
email = forms.EmailField(
label=_("Your Email"),
widget=forms.EmailInput(attrs={'class': 'form-control'}),
)
message = forms.CharField(
label=_("Message"),
widget=forms.Textarea(attrs={'class': 'form-control'}),
)
```
在这个例子中,我们在每个字段的widget参数中添加了class属性,这个class属性的值为form-control,这样就可以使用Bootstrap样式来美化表单组件。
最后,在HTML模板中使用Bootstrap样式:
```html
{% extends "base.html" %}
{% block content %}
<div class="container">
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
{% endblock %}
```
在这个例子中,我们使用了Bootstrap的container类和btn类来美化HTML模板。然后使用form.as_p来渲染表单组件,这个方法会把每个表单组件渲染成一个p标签,每个p标签中包含一个label标签和一个input标签,这样我们就可以使用Bootstrap样式来美化整个表单了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)