0

この CSRF の失敗を回避する方法がわかりません。読み続けている {% csrf_token %} を含めましたが、それでもこのエラーが発生します。コードは次のとおりです。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Log in</title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <style>
        body{
        font-family:Arial,Helvetica,sans-serif;
            font-size: 12px;
        }
    </style>
    </head>
    <body>
        {{ state }}
        <form action="/login/" method="post">{% csrf_token %}
            {% if next %}
            <input type="hidden" name="next" value="{{ next }}" />
            {% endif %}
            username:
            <input type="text" name="username" value="{{ username}}" /><br />
            password:
            <input type="password" name="password" value="" /><br />

            <input type="submit" value="Log In" />
        </form>
    </body>
</html>

これに適切な機能をすべて含めましたが、さらにコードを見る必要がある場合はお知らせください...ただし、これがすべて当てはまると思います...

編集:views.py

from django.shortcuts import render_to_response
from django.contrib.auth import *

def login_user(request):
  state = "Please log in below..."
  username = password = ''
  if request.POST:
      username = request.POST.get('username')
      password = request.POST.get('password')

      user = authenticate(username=username, password=password)
      if user is not None:
          if user.is_active:
              login(request, user)
              state = "You're successfully logged in!"
          else:
              state = "Your account is not active, please contact the site admin."
      else:
          state = "Your username and/or password were incorrect."

  return render_to_response('auth.html',{'state':state, 'username': username})
4

2 に答える 2

3

テンプレートコンテキストにトークンを追加し、このようなことを試して、質問へのコメントにリンクされているドキュメント/チュートリアルを読む必要があります。

from django.core.context_processors import csrf

def login_user(request):
    ...your code...
    ctx = {'state':state, 'username': username}
    ctx.update(csrf(request))
    return render_to_response('auth.html',ctx)
于 2013-03-09T01:08:48.513 に答える
0

ビューで、context_instance次のようにテンプレートに a を返します

from django.template import RequestContext
def login_user(request):
    ...
    return render_to_response('auth.html',{'state':state, 'username':
     username},context_instance=RequestContext(request))
于 2013-03-09T05:01:43.997 に答える