2014-11-10 7 views
-1

Я получаю эту ошибку, пока я вводил кнопку отправки в форме входа Запрещено (403) Ошибка CSRF. Запрос прерван. Причина, указанная для отказа: токен CSRF отсутствует или неверен.Как исправить ошибку CSRF в django python?


login.html

<form method="post" action="/index/">{% csrf_token %} 
    <table border="0"> 
     <tr><th><label for="id_username">Username:</label></th><td></td></tr> 
     <tr><th><label for="id_password">Password:</label></th><td></td></tr> 
    </table> 
    <input type="submit" value="Login" /> 
    <input type="hidden" name="next" value="/home" /> 
</form> 

views.py

def user_login(request): 
    # Like before, obtain the context for the user's request. 
    context = RequestContext(request) 

    # If the request is a HTTP POST, try to pull out the relevant information. 
    if request.method == 'POST': 
     # Gather the username and password provided by the user. 
     # This information is obtained from the login form. 
     username = request.POST['username'] 
     password = request.POST['password'] 

     # Use Django's machinery to attempt to see if the username/password 
     # combination is valid - a User object is returned if it is. 
     user = authenticate(username=username, password=password) 

     # If we have a User object, the details are correct. 
     # If None (Python's way of representing the absence of a value), no user 
     # with matching credentials was found. 
     if user: 
      # Is the account active? It could have been disabled. 
      if user.is_active: 
       # If the account is valid and active, we can log the user in. 
       # We'll send the user back to the homepage. 
       login(request, user) 
       return HttpResponseRedirect('/login/') 
      else: 
       # An inactive account was used - no logging in! 
       return HttpResponse("Your Rango account is disabled.") 
     else: 
      # Bad login details were provided. So we can't log the user in. 
      print "Invalid login details: {0}, {1}".format(username, password) 
      return HttpResponse("Invalid login details supplied.") 

    # The request is not a HTTP POST, so display the login form. 
    # This scenario would most likely be a HTTP GET. 
    else: 
     # No context variables to pass to the template system, hence the 
     # blank dictionary object... 

     return render_to_response('login/login.html', {}, RequestContext(request)) 
+0

Вы следовали рекомендациям, указанным на этой странице с ошибкой? В нем есть полное объяснение возможных причин и решений. –

+0

Я проверил свой код на основе этих инструкций ... все-таки я не могу исправить ... – Kalaiarasi

+0

Затем вам нужно показать свое мнение и соответствующую часть шаблона. Мы не можем догадываться, что не так с вашим кодом, не видя этого. –

ответ

0

Добавить CSRF маркер в виде

<form id="login_form">{% csrf_token %}</form> 
+0

Я уже использовал это, но все же я получаю ошибку – Kalaiarasi

1

Когда вы POST данные из HTML-формы в Django, и включена CSRF, вам необходимо включить в формфакторе token:

{% csrf_token %} 

Reference docs.

+0

Да, я уже использовал это в своем коде ... – Kalaiarasi

+0

\t {% csrf_token%} \t \t имя пользователя: <входной тип = "текст" имя = "имя пользователя" значение = "" размер = "30" /> \t \t

\t \t Password: <тип = вход "имя пароль" = «пароль» = «" размер = "30" /> \t \t

\t \t \t \t \t
Kalaiarasi