user1592380
user1592380

Reputation: 36367

Django bootstrap modal after form submission

I am working with django and have a bootstrap3 'contact' form that I submit after jquery validation. This is working correctly and I now want to redirect to a bootstrap modal 'thank you' page. I'm not exactly sure how to do this in Django. In my main page, under the form I've added:

        <div class="row">
            <div class="col-lg-5 col-lg-offset-1 col-sm-push-6  col-sm-6"
                <div class="clearfix"></div>
                <h2 class="section-heading">Registration form</h2>
                      {% block 'form' %}
                    {% endblock %}
            </div>
             <a data-toggle="modal" href="#thanksModal">thanksModal</a>
            {% include "thanks.html" %}
            <div class="col-lg-5 col-sm-pull-6  col-sm-6">
                <img class="img-responsive" src="../static/img/dog.png" alt="" />
            </div>
        </div>

The modal itself is:

<div class="modal hide" id="thanksModal">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">×</button>
  </div>
  <div class="modal-body">
      <h1>Thank you</h1>

  </div>
  <div class="modal-footer">
       <input name="cancel" class="btn" type="submit" value="Cancel"/>
  </div>
</div>

In my view I have:

def contact(request):
  errors = []
  if request.method == 'POST'

    if not request.POST.get('subject', ''):
        errors.append('Enter a subject.')
    if not request.POST.get('message', ''):
        errors.append('Enter a message.')
    if request.POST.get('email') and '@' not in request.POST['email']:
        errors.append('Enter a valid e-mail address.')
    if not errors:
        send_mail(
            request.POST['subject'],
            request.POST['message'],
            request.POST.get('email', '[email protected]'),
            ['[email protected]'], #email address where message is sent.
        )
        return HttpResponseRedirect('/thanks/')
return render(request, 'form.html',{'errors': errors})

def thanks(request):
    return render_to_response('thanks.html')

As it is currently, I see an unclickable link that says 'thank you' on the main page and upon submission a redirection occurs to the 'contact' page. How can I get this working?

Upvotes: 0

Views: 2462

Answers (1)

dotcomly
dotcomly

Reputation: 2214

If I understand correctly, after the contact form is submitted you want a modal to appear saying thanks.

Instead of:

return HttpResponseRedirect('/thanks/')

Do:

import json
...
return HttpResponse(json.dumps({"success":True}), content_type="application/json")

And in your JS that submits the form check the response for success before reloading the HTML form:

if (typeof jqXhr.success != 'undefined') {
    $('#success-modal').modal('show');
} else {
    $('#my-form').html(jqXhr);
}

Upvotes: 1

Related Questions