我正在尝试使用Crispy Forms
让我的表单看起来很棒。我的forms.py
:
from django import forms
from .models import Team
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Field
from crispy_forms.bootstrap import (
PrependedText, PrependedAppendedText, FormActions)
class CreateTeamForm(forms.ModelForm):
class Meta:
model = Team
fields = [ 'Project_name', 'Project_number'
]
helper = FormHelper()
helper.add_input(Submit('submit', 'Submit', css_class='btn-primary'))
helper.form_method = 'POST'
然后在我的views.py
:
def create_team(request):
if request.method == 'POST':
form = CreateTeamForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return render('/teams/my_team.html',{''})
else:
form = CreateTeamForm()
return render(request, 'teams/team_form.html', {'form':CreateTeamForm()})
最后在我的模板中:
{% extends "main/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="row">
<div class="jumbotron">
{% crispy form %}
</div>
</div>
{% endblock %}
但是,我调用的提交按钮未显示。我已阅读了cripsy表单文档,我似乎无法发现我的实现有任何问题。显示除提交按钮以外的所有内容。有什么想法吗?
答案 0 :(得分:6)
您的FormHelper
应该是表单类的属性,而不是其Meta
类。这是你代码的一部分:
class CreateTeamForm(forms.ModelForm):
class Meta:
model = Team
fields = [ 'Project_name', 'Project_number' ]
helper = FormHelper()
helper.add_input(Submit('submit', 'Submit', css_class='btn-primary'))
helper.form_method = 'POST'
答案 1 :(得分:2)
此解决方案适合我
from django.forms import ModelForm
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
class BillForm(ModelForm):
def __init__(self, *args, **kwargs):
super(BillForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit', css_class='btn-primary'))
self.helper.form_method = 'POST'
class Meta:
model = Bill
fields = ('__all__')
您在此示例后面的__init__
方法中定义了帮助器,然后将其放在模板中:
{% load crispy_forms_tags %}
{% crispy form %}
在你的观点/行动中你应该有类似的东西
form = BillForm()