Ошибка токена csrf для представлений на основе классов в django
Ошибка CSRF TOKEN для представлений на основе классов
Я создаю CRUD-модель, используя представления на основе классов. Для создания я использовал представление на основе классов, CreateView и шаблон crispy при отображении его в html-файле. Но по какой-то причине при развертывании кода в среде разработки я получаю следующую ошибку:
CSRF verification failed. Request aborted.
Reason given for failure:
Origin checking failed
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.
Я прошел через все вышеупомянутые пункты ошибки и убедился, что выполнил их все. Проблема в том, что я не могу переписать контекст с помощью представлений, основанных на классах. Есть предложения по решению этой проблемы?
views.py
# Create group
class PermissionCreateView(CreateView):
model = AadGroups
template_name = 'permissions/permissions_create.html'
fields = '__all__'
success_url = lazy(reverse, str)("permissions_manage")
# Save username when user created
def form_valid(self, form):
obj = form.save(commit=False)
user = self.request.session.get('user')
obj.username = user.get('email')
obj.save()
return super().form_valid(form)
urls.py
from django.urls import path
from permissions.views import *
from . import views
urlpatterns = [
path('permissions/manage/', ManagePermissionsListView.as_view(), name="permissions_manage"),
path('permissions/create/', PermissionCreateView.as_view(), name="permissions_create"),
path('permissions/update/<int:pk>/', PermissionUpdateView.as_view(), name="permissions_update"),
path('permissions/delete/<int:pk>/', PermissionDeleteView.as_view(), name="permissions_delete")
]
permissions_create.html
{% extends 'layout.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<div class="row justify-content-center">
<div class="col-8">
<h1 class="mt-2">Form for Creation</h1>
<hr class="mt-0 mb-4">
<form method="POST" enctype="multipart/form-data">
<!-- Security token -->
{% csrf_token %}
<!-- Using the formset -->
{{ form |crispy}}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
{% endblock %}