Contactform in footer of page

元气小坏坏 提交于 2019-12-24 20:05:04

问题


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}

Tips would be appreciated.


回答1:


It looks like you are returning the template tag's context without the form whenever someone submits a form.

See below:

  • 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', 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
    

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).



来源:https://stackoverflow.com/questions/48370597/contactform-in-footer-of-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!