1

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 href="#" class="btn siteBtn" >Sign Up</a>
            <p class="text-center">Don’t Have an account? <a 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!

11
  • Check your browser inspector (eg chrome developer tools) and see if there's csrf_token in post request data. + see if additional <input> rendered in form. Also paste more from views.py, code that you posted is unclear. Commented Dec 6, 2018 at 7:42
  • where is the view where you are posting data Commented Dec 6, 2018 at 7:47
  • Hi @Exprator, I have added the code for post also. take a look, please! Commented Dec 6, 2018 at 8:15
  • The browser inspector shows that the post data as : password abd37214 username abdul002 Commented Dec 6, 2018 at 8:17
  • 1
    In your method == 'GET' section change 3 lines to single one: return render(request, 'login.html') import is: from django.shortcuts import render. Will that work for you? Commented Dec 6, 2018 at 8:39

1 Answer 1

3

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')
Sign up to request clarification or add additional context in comments.

1 Comment

The correct way to render the template with the request is temp.render(request=request), but it's simpler to use the render shortcut like you have suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.