CSRF验证失败。请求中止。 django python3 html中的{%csrf_token%}

时间:2017-05-19 20:05:05

标签: python html django

我正在尝试使用django / python登录。

我在views.py中有这个:

@csrf_exempt
def Principal(request):
    context = {}
    if request.method != 'GET':
        context = {
            'title': '405 Method Not Allowed',
        }


    if request.user.is_authenticated():
        logged_q = 'Logged in as '+ request.user.username
        logged = True
    else:
        logged_q = 'Not logged in.'
        logged = False

    print (logged_q)

    top_aparcamientos = Aparcamiento.objects.all()
    #top_aparcamientos = Comentario.objects.all().order_by('-aparcamiento__id').unique()[:5]
    pagina_list = Pagina.objects.all()       

    context['top_aparcamientos'] = top_aparcamientos
    context['pagina_list'] = pagina_list
    usuario = request.user.username
    context = {
      'usuario' : usuario,
      'logged' : logged
    }


    return render_to_response('index.html', context

所以,为了做我的模板,我把这个变量记录在我的base.html中:

{% if logged %}
    <div class ="container_corner">
        <div class="topright">
            <span id="corner_message"><strong>Bienvenido,</strong>&nbsp<span class="oblicuo">{{usuario}}</span></span>
            <a href='logout/'><button id="logged"type="submit">Salir</button></a><br>
        </div>
    </div> {% else %}
    <form id="login_form" action="login/" method ="POST">
        {% csrf_token %}
        <label for="id_username"><span class="login_fields">Nick: </span></label> <input id="id_username" maxlength="254" name="username" type="text" />
        <label for="id_password"><span class="login_fields">Contraseña: </span></label> <input id="id_password" name="password" type="password" />
        <button type="submit">Login</button>
    </form> {% endif %}

但是当我尝试登录时,它会给我这个错误:

Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect.

我还需要{% csrf_token %}吗?在哪里?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用

代替{%csrf_token%}
<input type='hidden' name='csrfmiddlewaretoken' value='{{ csrf_token }}' />

或者您也可以使用{{csrf_input}}。

<form action="login/" method="post">{{ csrf_input }}