Ad

Django CSRF Verification Failed Even After Adding Csrf_token Tag Inside The Form Html

- 1 answer

I'm working on a project using Python(2.7) and Django(1.10) in which I need submit the login form but it returns an error on submission.

Note: I have searched a lot of questions tried various answers but in most cases the {% csrf_token %} is missing from the <form> HTML but in my case, I'm using this also, that's why don't mark this question duplicated, please!

Here's what I have tried:

from form.html:

<form class="fields-signup" action="{% url 'mainlogin' %}" method="post">


{% csrf_token %}
            <h1 class="text-center">Sign In</h1>
            <div class="form-group">
                <input class="user-name form-control" type="text"  name="username" placeholder="User name">
            </div>
            <div class="form-group">
                <input class="password form-control" type="password"   placeholder="Password" name="password">
            </div>
            <input type="submit" class="btn siteBtn" value="Sign In">
            <!-- <a target="_blank" rel="nofollow noreferrer" href="#" class="btn siteBtn" >Sign Up</a>
            <p class="text-center">Don’t Have an account? <a target="_blank" rel="nofollow noreferrer" href="#">Signup</a></p> -->


            <!--popup-forget-password-->
            <div class="col-sm-12">
             <button type='button' class="forget-password-btn" data-toggle="modal" data-target="#popUpWindow">Forgot Password</button> 
              <!--forget-password-end-->
                <div class="col-sm-12 register">
                 <a class="register-driver-btn" data-toggle="modal" data-target="#popUpWindow_register">Register Driver?</a> 
                </div>
            </div>
</form>

from urls.py:

url(r'^$', views.home, name="home"),

from views.py:

    if request.method == "GET":
    try:
        temp = get_template('login.html')
        result = temp.render(Context({'context': RequestContext(request)}))
        return HttpResponse(result)

more from views.py:

    if request.method == "POST":
    username = request.POST['username']
    # email = request.POST['email']
    password = request.POST['password']
    try:
        #obj = User_table.objects.get(user_name=username, emailid=email)
        obj = User_table.objects.get(user_name=username)
        if obj:
            print('got user obj')
        verify_password = ''
        try:
            verify_password = handler.verify(password, obj.password)
        except Exception as e:
            print(e)
        if verify_password is True:
            request.session['user_id'] = obj.id
            request.session['user_type'] = obj.user_type
            user_name = obj.first_name + ' ' + obj.last_name
            request.session['user_name'] = user_name
            if not obj.approval_status:
                return HttpResponse('Your account is not confirmed by administration.')
            obj.is_active = True
            obj.login_try = 0
            obj.save()
            return redirect(home)
        else:
            try:
                # obj = User_table.objects.get(user_name=username, emailid=email)
                obj = User_table.objects.get(user_name=username)
                if obj:
                    s = obj.login_try
                    s = s + 1
                    obj.login_try = int(s)

                    if int(obj.login_try) >= 3:
                        obj.login_try = 3
                    obj.save()
                    if int(obj.login_try) == 3:
                        id = obj.id
                        key = get_random_string(length=10)
                        reset_link = 'It seems you forgot password or someone is trying to login you account. This is your password reset link please do not share this with other ' + settings.EMAIL_URL + 'reset_password/' + str(
                            id) + ' key is : ' + str(key)
                        send_mail('Reset link', reset_link, settings.EMAIL_HOST_USER, [obj.emailid, ])
                        obj.password = str(key)
                        obj.save()
                        return HttpResponse(
                            'It seems you forgot password or someone is trying to login you account.  Password Reset link has been sent to your email id')
            except Exception as e:
                print(e)
                pass
            return redirect(mainlogin)
    except Exception as e:
        print('error is  : ', e)
        return HttpResponse('An error has occurred.')

Also, I have included the csrf middleware in my settings.py. what can be wrong here?

Thanks in advance!

Ad

Answer

Your problem is here:

if request.method == "GET":
    try:
        temp = get_template('login.html')
        result = temp.render(Context({'context': RequestContext(request)}))
        return HttpResponse(result)

Docs about CSRF

In the corresponding view functions, ensure that RequestContext is used to render the response so that {% csrf_token %} will work properly. If you’re using the render() function, generic views, or contrib apps, you are covered already since these all use RequestContext.

I'm not exactly sure why it's happening, maybe something wrong with context processors configuration, one of them adds csrf_token to context dictionary. For more debugging see RequestContext section. But using builtin render() function will solve your problem as it'll handle context for you.

from django.shortcuts import render
if request.method == "GET":
    ...
    return render(request, 'login.html')
Ad
source: stackoverflow.com
Ad