我正在处理Django应用程序。在申请中存在一种缴费表格。我用django模型和django表单创建了表单。但是,当我尝试运行该应用程序时,出现以下错误。
crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field
我不确定自己在做什么错。
CONTRIBUTE_CHOICE = (
('Books', 'Books'),
('Renovation', 'Renovation'),
('Other', 'Other'),
)
class Contribute(models.Model):
firstName = models.CharField(max_length=50)
lastName = models.CharField(max_length=50)
email = models.EmailField(max_length=100)
contribution = models.CharField(max_length=100, choices=CONTRIBUTE_CHOICE)
def publish(self):
self.save()
def __str__(self):
return self.firstName
from .models import Contribute
CONTRIBUTE_CHOICE = (
('Books', 'Books'),
('Renovation', 'Renovation'),
('Other', 'Other'),
)
class ContributeForm(forms.ModelForm):
contribution = forms.ChoiceField(choices=CONTRIBUTE_CHOICE, required=True )
class Meta:
model = Contribute
widgets = {
'firstName': forms.TextInput(attrs={'placeholder': 'First Name'}),
'lastName': forms.TextInput(attrs={'placeholder': 'Last Name'}),
'email': forms.TextInput(attrs={'placeholder': 'Email'}),
}
fields = ('firstName', 'lastName', 'email', 'contribution')
from .forms import ContributeForm
def donate(request):
if request.method == "POST":
contributeForm = ContributeForm(request.POST)
if contributeForm.is_valid():
post = contributeForm.save(commit=False)
post.save()
return redirect('home')
else:
contributeForm = ContributeForm()
context = {'contributeForm': contributeForm}
return render(request, 'donate.html', context)
<form class='contribution_form' method="post">
{% csrf_token %}
<div class="row">
<div class="col">
{{ contributeForm.firstName|as_crispy_field }}
</div>
<div class="col">
{{ contributeForm.lastName|as_crispy_field }}
</div>
</div>
{{ contributeForm.email|as_crispy_field }}
{{ contributeForm.contribution|as_crispy_field }}
<button type="submit" class="btn btn-lg">Submit</button>
</form>
This是我创建表单所遵循的链接
django.template.exceptions.TemplateSyntaxError: Invalid filter: 'as_crispy_field'
答案 0 :(得分:1)
您没有将表单传递给donate.html模板:
def donate(request):
if request.method == "POST":
contributeForm = ContributeForm(request.POST)
if contributeForm.is_valid():
post = contributeForm.save(commit=False)
post.save()
return redirect('home')
else:
# this should be include if form validate failed
return render(request, 'donate.html', {'contributeForm': contributeForm})
elif request.method == "GET":
contributeForm = ContributeForm()
context = {'contributeForm': contributeForm}
# return render(request, 'index.html', context) <-- why do you have this here?
return render(request, 'donate.html', context)
答案 1 :(得分:0)
我有同样的错误信息。这是一个ForeignKey类型的变量/表单字段,它应该显示选择,导致了问题。
答案 2 :(得分:0)
您的表单名称是:
<块引用>投稿表格
并在您编写的模板中:
<块引用>投稿表格
是按键敏感的问题