1

ユーザーがログインできるようにする簡単なフォームがあります。CSRFタグを含むテンプレートコードは次のとおりです。

<html>
<head><title>My Site</title></head>

<body>
    <form action="" method="post">{% csrf_token %}
        <label for="username">User name:</label>
        <input type="text" name="username" value="" id="username">
        <label for="password">Password:</label>
        <input type="password" name="password" value="" id="password">

        <input type="submit" value="login" />
        <input type="hidden" name="next" value="{{ next|escape }}" />
    </form>
</body>
</html>

これが私のviews.pyページです。問題は、CSRFサポート部分(現在、CFRSトークンエラーが発生する)を自分のビューのどこに配置するのか、そしてどのように行うのかということです。

from django.contrib import auth

def login_view(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(username=username, password=password)
    if user is not None and user.is_active:
        # Correct password, and the user is marked "active"
        auth.login(request, user)
        # Redirect to a success page
        return HttpResponseRedirect("/account/loggedin/")
    else:
        # Show an error page
        return HttpResponseRedirect("account/invalid/")

def logout_view(request):
4

1 に答える 1

5

線が含まれているページをレンダリングするRequestContextビューにを追加する必要があります。チュートリアルの例を次に示します。{% csrf_token %}

# The {% csrf_token %} tag requires information from the request object, which is 
# not normally accessible from within the template context. To fix this, 
# a small adjustment needs to be made to the detail view, so that it looks 
# like the following:
#
from django.template import RequestContext
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p},
                           context_instance=RequestContext(request))

そのcontext_instance=RequestContext(request)部分は重要な部分です。これにより、リクエストコンテキストがレンダリング時にフォームテンプレートで使用できるようになります。

于 2010-10-21T00:57:34.870 に答える