Ad

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}

Tips would be appreciated.

Ad

Answer

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

Ad
source: stackoverflow.com
Ad