Ошибка Django 403 после отправки формы смены пароля («CSRF использовался неправильно») (может быть из-за .asview ()) - PullRequest
0 голосов
/ 25 апреля 2019

После отправки PasswordChangeForm я получаю ответ 403:

    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.

Мой HTML-шаблон:

    {% extends 'rango/base.html' %}

    {% block body_block %}
            <h1>Change your password</h1>
            <form method="post" action =".">
                {% csrf_token %}
                {{ form.as_p }}
                <input type="submit" value="Submit" />
            </form> 
    {% endblock %}

Работают другие шаблоны, расширяющие базу.

Промежуточное программное обеспечение включает в себя «django.middleware.csrf.CsrfViewMiddleware».

Views.py не имеет паролей и паролей.

Скорее, я попытался внедрить Django в файл url через импорт и функцию asview (). Пожалуйста, посмотрите последние 2 URL и не стесняйтесь игнорировать мои комментарии к себе:

    # created this urls.py in rango for rango to handle urls (see p 24)

    # needed to add include in c11 to work with registration 
    from django.conf.urls import url, include
    from rango import views
    # backends added c11 to override login redirect page
    from registration.backends.simple.views import RegistrationView
    from django.contrib.auth.forms import PasswordChangeForm #NECESSARY HERE?
    from django.contrib.auth.views import PasswordChangeView, PasswordChangeDoneView

    class MyRegistrationView(RegistrationView):
        def get_success_url(self, request, user):
            return '/rango/'

    #updated patterns in c6 to account for slugs
    #patterns has been deprecated - > issue 
    #changed to just a list
    urlpatterns = [
        url(r'^$', views.index, name='index'),
        url(r'^about/', views.about, name='about'),
        #?P makes group to match the slug 
        url(r'^category/(?P<category_name_slug>[\w\-]+)/$',
        views.show_category, name='show_category'),
        #next added at c7 for forms
        #ordering may matter for processing of requests -- see official docs 
        url(r'^add_category/$', views.add_category, name='add_category'),
        url(r'^category/(?P<category_name_slug>[\w\-]+)/add_page/$', views.add_page, name='add_page'),
        #added c9 for registration
        url(r'^register/$', views.register, name='register'),
        #added c9 for login
        url(r'^login/$', views.user_login, name='login'),
        url(r'^restricted/$', views.restricted, name='restricted'),
        url(r'^logout/$', views.user_logout, name='logout'),
        #c11 after adding class above to redirect
        url(r'^accounts/register/$',
            MyRegistrationView.as_view(),
                name='registration_register'),
        # needed to add include import (c11 registration)
        url(r'^accounts/', include('registration.backends.simple.urls')),
        url(r'^password/change', PasswordChangeView.as_view(), name='password_change'),
        url(r'^password/change/done', PasswordChangeDoneView.as_view(), name='password_change_done'),

        ]

Другие URL работают.

В окне cmd отсутствует трассировка.

Может кто-нибудь сказать мне, что я упустил? Спасибо.

...