页面页脚中的联系表单 [英] Contactform in footer of page
问题描述
我在网站的页脚中有一个联络表。每一页上都有。它起作用了,但有一个问题:发送后,它就不再显示了。更具体地讲,我想当我的请求不再为空时。
I have a contactform in the footer of a website. So it is on every page. It works, with one problem: as soon as it is sent, it doesn't show anymore. More specific I guess when my request is no longer empty.
@register.inclusion_tag('home/tags/contact.html', takes_context=True)
def contact_form(context):
request = context['request']
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['naam']
from_email = form.cleaned_data['email']
message = form.cleaned_data['bericht']
messages.success(request, 'Form submission successful')
try:
send_mail(subject, message, from_email, ['myemailaddress'])
except BadHeaderError:
return HttpResponse('invalid header found')
return context
else:
form = ContactForm()
return {request: 'context.request', 'form': form}
提示将不胜感激。
推荐答案
它看起来像你每当有人提交表单时,都会重新返回没有表单
的模板标签的上下文。
It looks like you are returning the template tag's context without the form
whenever someone submits a form.
请参见下文:
- 在函数结束之前不要返回上下文对象,这将使事情更容易处理。
- 最好将键添加到上下文对象,这使您不必重新添加
请求
,因为它已经存在。 -
将else分支移到最后,即使在收到响应(通过POST)后,您也要一直发送新的(空白)表单。
- Do not return the context object until the end of the function, this will make things simpler to work through.
- Best to add keys to the context object, this saves you from having to re-add
request
because it is already there. Remove the else branch towards the end, you want to send a new (blank) form all the time, even after receiving a response (via POST).
@ register.inclusion_tag('home / tags / contact.html',take_context = True)
def contact_form(context):
request = context ['request']
@register.inclusion_tag('home/tags/contact.html', takes_context=True) def contact_form(context): request = context['request']
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['naam']
from_email = form.cleaned_data['email']
message = form.cleaned_data['bericht']
messages.success(request, 'Form submission successful')
try:
send_mail(subject, message, from_email, ['myemailaddress'])
except BadHeaderError:
return HttpResponse('invalid header found')
#return context # returning here sends back the context without 'form'
# remove the else branch, you always want to return an empty form
#else:
form = ContactForm()
# return {request: 'context.request', 'form': form}
# return at a consistent place in a consistent way
# add to context, rather then recreating it
context['form'] = form
return context
另一种解决方法是将重定向到联系人页面的URL处于开启状态(但是,您将丢失消息)。
Another workaround would be just to do a redirect back to the URL that the contact page is on (however, you will loose your messages).
这篇关于页面页脚中的联系表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!