在页脚的页面中的Contactform

时间:2018-01-21 19:05:15

标签: django django-forms django-templates wagtail

我在网站的页脚中有一个联系表单。所以它在每一页上都有。它有效,有一个问题:一旦发送,它就不再显示了。当我的请求不再是空的时候,我想更具体。

@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}

提示将不胜感激。

1 个答案:

答案 0 :(得分:1)

当有人提交表单时,您似乎没有form返回模板标记的上下文。

见下文:

  • 在函数结束之前不要返回上下文对象,这样可以使事情变得更简单。
  • 最好向上下文对象添加密钥,这样您就不必重新添加request,因为它已经存在。
  • 在结束时删除else分支,即使收到回复(通过POST),也要始终发送新的(空白)表单。

    @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(但是,您将丢失消息)。