Search code examples
ajaxdjangotwitter-bootstrapdjango-templatesdjango-registration

Django - Ajax modal login/registration


I have a project in which I need to pop a modal window for not authenticated users.

This modal will allow to login directly or create an account.

So it will contain two forms:

  • django.contrib.auth.forms.AuthenticationForm
  • registration.forms.RegistrationForm

Modal tabbed forms

Here is my view to get both forms:

def ajax_registration(request):
    obj = {
        'login_form': AuthenticationForm(),
        'registration_form': RegistrationForm(),
    }
    return render(request, 'common/ajax_registration.html', obj)

And my template displaying the forms tabbed

<ul class="nav nav-tabs">
  <li><a href="#tab1" data-toggle="tab">{% trans 'Login' %}</a></li>
  <li><a href="#tab2" data-toggle="tab">{% trans 'Registration' %}</a></li>
</ul>
<div class="tab-content">
  <div class="tab-pane active" id="tab1">
    {{ login_form|bootstrap }}
  </div>
  <div class="tab-pane" id="tab2">
    {{ registration_form|bootstrap }}
  </div>
</div>

Question is: Since I'm using ajax to display this modal, How can I validate the selected form, preferably using the already written django-registrations register & django.contrib.auth login views ?


Solution

  • In addition to Maddog's answer you need some javascript to submit the form back to the URL that rendered the form. Using jquery it could be something like:

    $('form').submit(function(e){
            e.preventDefault();
            var form = $(e.target);
    
            $.ajax({
                url: '{% url YOUR_REGISTRATION_URL %}',
                type: 'post',
                data: account_form.serialize() + '&' + form.serialize(),
                error: function(xhr, ajaxOptions, thrownError){ alert(thrownError); },
                success: function(){}
            })
     })
    

    You don't need to do it with a form submit element, you could use any element with $().click(), of course.