django-crispy-forms入门指南

时间:2023-03-10 05:24:27
django-crispy-forms入门指南

django-crispy-forms 是对django form在html页面呈现方式进行管理的一个第三方插件。

配置: 在INSTALLED_APPS中加入'crispy_forms'

django-crispy-forms可以选择四种css库,分别是bootstrap,bootstrap3,uni-from以及foundation,当你选定一种后,你需要在settings.py中设置,例如

CRISPY_TEMPLATE_PACK = 'bootstrap'

django-crispy-forms不再将静态的css以及js文件包括进来,需要自己去下载,并将其放入你的静态文件夹里。

一个model实例:

class MessageForm(forms.Form):
text_input = forms.CharField()
textarea = forms.CharField(
widget = forms.Textarea(),
)
radio_buttons = forms.ChoiceField(
choices = (
('option_one', "Option one is this and that be sure to include why it's great"),
('option_two', "Option two can is something else and selecting it will deselect option one")
),
widget = forms.RadioSelect,
initial = 'option_two',
)
checkboxes = forms.MultipleChoiceField(
choices = (
('option_one', "Option one is this and that be sure to include why it's great"),
('option_two', 'Option two can also be checked and included in form results'),
('option_three', 'Option three can yes, you guessed it also be checked and included in form results')
),
initial = 'option_one',
widget = forms.CheckboxSelectMultiple,
help_text = "<strong>Note:</strong> Labels surround all the options for much larger click areas and a more usable form.",
)
appended_text = forms.CharField(
help_text = "Here's more help text"
)
prepended_text = forms.CharField()

prepended_text_two = forms.CharField()
multicolon_select = forms.MultipleChoiceField(
choices = (('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5')),
)
helper = FormHelper()
helper.form_class = 'form-horizontal'
helper.layout = Layout(
Field('text_input', css_class='input-xlarge'),
Field('textarea', rows="3", css_class='input-xlarge'),
'radio_buttons',
Field('checkboxes', style="background: #FAFAFA; padding: 10px;"),
AppendedText('appended_text', '.00'),
PrependedText('prepended_text', '<input type="checkbox" checked="checked" value="" id="" name="">', active=True),
PrependedText('prepended_text_two', '@'),
'multicolon_select',
FormActions(
Submit('save_changes', 'Save changes', css_class="btn-primary"),
Submit('cancel', 'Cancel'),
)
)

在Html中使用:

{% load crispy_forms_tags %}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/static/media/css/bootstrap.min.css" type="text/css">
<meta charset="UTF-8">
<title></title>
</head>
<body>
{% crispy form %}
</body>
</html>

效果图:

django-crispy-forms入门指南