Question: Django AJAX login form validation

Question

Django AJAX login form validation

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

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:

urls.py

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

forms.py

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

    class Meta:
        model = User

        fields = [
            'username',
            'password',
        ]

base.html

<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"/>
    </div>
</div>
</div>
</form>

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

base.js

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

    $.ajax({
        type: 'POST',
        url: 'http://127.0.0.1:8000/user_login/',
        data: {'username': $('.login_username').val(),
                'password': $('.login_password').val()},
        success: function (data) {
            console.log(data)
                }
        }
    )
})

How do I get the data from the jQuery function to my views.py? 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.

views.py

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)
        else:
            pass
    else:
        print(form_login.errors)
        print(form_login.non_field_errors)
        form_login = UserLoginForm()

    return redirect('/')

And then how do I authenticate the jQuery data in my views.py?

Answers to

Django AJAX login form validation

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'});
    else:
        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.

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