reagrding "{% csrf_token %}"issue on my web site login module

336 vistas
Ir al primer mensaje no leído

The Aryas

no leída,
28 may 2019, 7:33:13 a.m.28/5/2019
para Django users
hello guys, i was working on a clone project and got stuck on a problem. the {% csrf_token %} that i have applied is not verified ...and the error login module is following>>

====================================================================================================================================

Forbidden (403)

CSRF verification failed. Request aborted.

Help

Reason given for failure:

    CSRF token missing or incorrect.
    

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

  • Your browser is accepting cookies.
  • The view function passes a request to the template's render method.
  • In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
  • If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
  • The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.

You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting. 

================================================================================================================================

I have applied all the requirements but still that occurs. here is my code>>

<login.html>

{% extends 'blog/base.html' %}
{% block content %}
<div class="jumbotron">
  <h2>Please login!</h2>
  <h3>(must be suoer user , please check with site admin)</h3>
</div>
{% if forms.errors %}
  <p>Your user name and password did not match please try again!</p>
{% endif %}

<form action="{% url 'login' %}" method="POST">
{% csrf_token %}
{{ form.as_p }}
  <input type="submit" class="btn btn-primary" value="login">
  <input type="hidden" name="next" value="{{next}}">
</form>
{% endblock %}

===================================================================================
<urls.py- project(mysite)>


from django.contrib import admin
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from django.urls import path
from django.conf.urls import include
from django.contrib.auth import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('blog.urls')),
    path('accounts/login/',views.LoginView.as_view(), name='login'),
    path('accounts/logout/',views.LogoutView.as_view(), name='logout',kwargs={'next_page':'/'})
]

===================================================================================
<views.py>
from django.shortcuts import render,get_object_or_404,redirect
from django.utils import timezone
from blog.models import Post,Comment
from blog.forms import PostForm,CommentForm
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,
                                    DetailView,CreateView,
                                    UpdateView,DeleteView)
# Create your views here.

class AboutView(TemplateView):
    template_name='about.html'

class PostListView(ListView):
    model=Post

    def get_queryset(self):
        return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')


class PostDetailView(DetailView):
    model=Post

class CreatePostView(LoginRequiredMixin,CreateView):
    login_url='/login'
    redirect_field_name='blog/post_detail.html'

    form_class=PostForm

    model=Post


class PostUpdateView(LoginRequiredMixin,UpdateView):
    login_url='/login'
    redirect_field_name='blog/post_detail.html'

    form_class=PostForm

    model=Post


class PostDeleteView(LoginRequiredMixin,DeleteView):
    model=Post
    success_url=reverse_lazy('post_list')


class DraftListView(LoginRequiredMixin,ListView):
    login_url='/login/'
    redirect_field_name='blog/post_list.html'
    model=Post

    def get_queryset(self):
        return Post.objects.filter(published_date_isnull=True).order_by('created_date')

@login_required
def add_comment_to_post(request,pk):
    post=get_object_or_404(post,pk=pk)
    if request.method == 'POST':
        form=CommentForm(request.POST)
        if form.is_valid():
            Comment=form.save(commit=False)
            comment.post=post
            comment.save()
            return redirect('post_detail',pk=post.pk)
    else:
        form=CommentForm()
    return render(request,'blog/comment_form.html',{'form':form})
@login_required
def comment_approve(request,pk):
    comment=get_object_or_404(Comment,pk=pk)
    comment.approve()
    return redirect('post_detail',pk=comment.post.pk)
@login_required
def comment_remove(request,pk):
    comment=get_object_or_404(Comment,pk=pk)
    post_pk=comment.post.pk
    comment.delete()
    return redirect('post_detail',pk=post_pk)

@login_required
def post_publish(request,pk):
    post=get_object_or_404(Post,pk=pk)
    post.publish()
    return redirect('post_detail',pk=pk)
===========================================================================


guys plz help me out to run my code
thank you
 

isorae dennis

no leída,
28 may 2019, 7:56:40 a.m.28/5/2019
para django...@googlegroups.com
Did you indent accurately

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/1e2b9b83-7aab-46f5-867d-8de101777762%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jeyakanth T

no leída,
28 may 2019, 8:13:51 a.m.28/5/2019
para django...@googlegroups.com
Hi,
add one more line in your view.py header

from django.views.decorators.csrf import csrf_exempt


then add decorator  before your function

@csrf_exempt

With Regards,

Jeyakanth Thangam,

 +91 89739 - 70708, +91 79046 - 48182

jeyakanth0810@gmail.com



Abdulrasheed Ibrahim

no leída,
28 may 2019, 8:38:34 a.m.28/5/2019
para django...@googlegroups.com
For security reasons, It's not recommended to use csrf_exempt, use it only where security doesn't matter 

Abdul Qoyyuum

no leída,
30 may 2019, 10:33:29 a.m.30/5/2019
para Django users
When you run the application and test the login, what do you see in the devtool's Network tab? Did you see if csrf_token is null? How about document.cookie? Is that also null? Is the document.cookie being passed to csrf_token in other ways?

Lots of ways to complete this in Angular/jQuery/Ajax or otherwise is presented in this document: https://docs.djangoproject.com/en/2.2/ref/csrf/
Responder a todos
Responder al autor
Reenviar
0 mensajes nuevos