Question: Django AJAX login form validation


Django AJAX login form validation

Answers 1
Added at 2016-12-29 08:12

I'm trying to create an AJAX login form in Django, which would involve checking if the user has entered the correct username and password. Here is my code right now:

urlpatterns = [
    url(r'^$', views.boxes_view, name='news'),
    url(r'^user_login/', views.user_login, name='user_login'),

class UserLoginForm(forms.Form):
    username = forms.CharField(max_length=25)
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User

        fields = [


<form method="post" enctype="multipart/form-data" action="{% url 'user_login' %}" class="form_login">{% csrf_token %}
<div class="loginWrapper">
<div class="login">
    <div class="loginBox">
        {{ form_login.username|placeholder:"username"|add_class:"login_username" }}
        {{ form_login.password|placeholder:"password"|add_class:"login_password" }}

        <input type="submit" value="login"/>

Here is my jQuery function. It successfully logs the entered username and password to the console.


$('.form_login').on('submit', function(e) {

        type: 'POST',
        url: '',
        data: {'username': $('.login_username').val(),
                'password': $('.login_password').val()},
        success: function (data) {

How do I get the data from the jQuery function to my Here is my current views which works fine to log a user in, however if the wrong credentials are entered it just submits the form anyway, which is why I want to implement AJAX to prevent submission and list errors if this happens.

def user_login(request):
    form_login = UserLoginForm(request.POST or None)
    if form_login.is_valid():
        username = form_login.cleaned_data['username']
        password = form_login.cleaned_data['password']
        user = authenticate(username=username, password=password)
        if user is not None and user.is_active:
            login(request, user)
        form_login = UserLoginForm()

    return redirect('/')

And then how do I authenticate the jQuery data in my

nr: #1 dodano: 2016-12-29 08:12

First of all you shouldn't be writing your own registration/authentication system. There are quite a few tried and tested solutions out there. Django Allauth comes to mind immidiately.

Second, if you are sending the login data while ajax, you would want the view to return an ajax response

    if user is not None and user.is_active:
        login(request, user)
        return JsonResponse({'status': 'ok'});
        return JsonResponse({'status': 'login failed'});

Then in your form invalid section you are merely redirecting to another page. That doesn't work very well with ajax.

    return JsonResponse(form_login.errors.as_json())
Source Show
◀ Wstecz