我有一个没有关联模型的表单,只是一个用于发送消息的联系表单。
到目前为止,我对django表单已有一定的经验,所以我认为我已经正确地完成了所有操作,但是当完全在浏览器中查看页面时,最终结果还是没有呈现。
我的forms.py:
from django import forms
class ContactForm(forms.Form):
class Meta:
fields = ['full_name', 'phone', 'email', 'message']
full_name = forms.CharField(max_length=20)
phone = forms.CharField(max_length=20)
email = forms.CharField(max_length=30)
message = forms.CharField(max_length=400)
我的观点将表单变成了有用的东西:
def contact_view(request):
full_name = request.POST.get('full_name', False)
phone = request.POST.get('phone', False)
email = request.POST.get('email', False)
message = request.POST.get('message', False)
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# send_emails(first_name, last_name, email)
template = loader.get_template('/myapp/mysite/main_page/templates/main_page/thankyoumsg.html')
return HttpResponse(template.render({}, request))
template = loader.get_template('/myapp/mysite/main_page/templates/main_page/contact.html')
return HttpResponse(template.render({}, request))
还有我的模板:
<form class="leave-comment" action="." method="post">
{% csrf_token %}
{{form.as_p}}
<button type="submit">Submit</button>
</form>
但是什么也没显示,我不确定为什么。我该如何解决这个问题?
答案 0 :(得分:1)
您未在最后一行的响应中包含该表格。这应该(可能)达到目的:
def contact_view(request):
...
return HttpResponse(template.render({'form': form}, request))
我还认为您需要将字段直接添加到表单类中,而不是在元类中。
from django import forms
class ContactForm(forms.Form):
# Move out the fields here instead
full_name = forms.CharField(max_length=20)
phone = forms.CharField(max_length=20)
email = forms.CharField(max_length=30)
message = forms.CharField(max_length=400)
class Meta:
# This may still be there but may also be a bit redundant since
# you're choosing to show all applied fields.
fields = ['full_name', 'phone', 'email', 'message']
答案 1 :(得分:1)
类别元仅在拥有模型时使用。如果只需要呈现一个没有特定模型的表单,请使用这种方式。有关更多信息,请访问官方文档: https://docs.djangoproject.com/en/2.1/topics/forms/
forms.py
class ContactForm(forms.Form):
full_name = forms.CharField(max_length=20)
phone = forms.CharField(max_length=20)
email = forms.CharField(max_length=30)
message = forms.CharField(max_length=400)
views.py
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
full_name = form.cleaned_data['full_name']
phone = form.cleaned_data['phone']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
template = loader.get_template('/myapp/mysite/main_page/templates/main_page/thankyoumsg.html')
return HttpResponse(template.render({'form': form}, request))
template = loader.get_template('/myapp/mysite/main_page/templates/main_page/thankyoumsg.html')
return HttpResponse(template.render({'form': form}, request))
form = ContactForm()
template = loader.get_template('/myapp/mysite/main_page/templates/main_page/contact.html')
return HttpResponse(template.render({'form': form}, request))