简体   繁体   中英

CSRF verification failed. Request aborted. {% csrf_token %} in django python3 html

I am trying to do a log in in django/python.

I have this in my 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

So, for do my template, I take the variable logged in my base.html like that:

{% 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 %}

But it gives me this error when I try to log in:

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

Do I need anymore {% csrf_token %} ? Where?

Thank you!

Instead of {% csrf_token %}, you can probably use

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

Or you can also use {{ csrf_input }}.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM