Не отображается шаблон: Method Not Allowed (GET): /account/logout/
Помогите пожалуйста разобраться в причине, по которой не отображается кастомный шаблон logout. Отмечу, что если я нажимаю на LOG OUT в админке джанго, то меня редиректит на шаблон, но не по адресу http://127.0.0.1:8000/account/logout/ а по http://127.0.0.1:8000/admin/logout/. Делаю все в точности как в книге Django 4 в примерах (страницы 200-205).
Console output:
Watching for file changes with StatReloader
System check identified no issues (0 silenced).
December 08, 2023 - 08:17:52
Django version 5.0, using settings 'bookmarks.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[08/Dec/2023 08:18:05] "GET /account/login/ HTTP/1.1" 200 1433
Method Not Allowed (GET): /account/logout/
Method Not Allowed: /account/logout/
[08/Dec/2023 08:18:17] "GET /account/logout/ HTTP/1.1" 405 0
/account/urls.py:
from django.urls import path, include
from django.contrib.auth import views as auth_views
from account import views
urlpatterns = [
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]
settings:
LOGIN_URL = 'login'
LOGOUT_URL = 'login' # Менял 'login' на 'logout' - не помогло.
INSTALLED_APPS = [
'account',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
account/templates/registration/logged_out.html:
{% extends 'base.html' %}
{% block title %}Logged out{% endblock %}
{% block content %}
<h1>Logged out</h1>
<p>
You have been succesfully logged out.
You can <a href="{% url 'login' %}">log-in again</a>
</p>
{% endblock %}
base.html:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link href="{% static "css/base.css" %}" rel="stylesheet">
</head>
<body>
<div id="header">
<span class="logo"><a href="{% url 'login' %}">Bookmarks</a></span>
{% if request.user.is_authenticated %}
<ul class="menu">
<li {% if section == "dashboard" %}class="selected" {% endif %}>
<a href="{% url "dashboard" %}">My dashboard</a>
</li>
<li {% if section == "images" %}class="selected" {% endif %}>
<a href="#">Images</a>
</li>
<li {% if section == "people" %}class="selected" {% endif %}>
<a href="#">People</a>
</li>
</ul>
{% endif %}
<span class="user">
{% if request.user.is_authenticated %} Hello {{ request.user.first_name|default:request.user.username }},
<a href="{% url "logout" %}">Logout</a>
{% else %}
<a href="{% url "login" %}">Log-in</a>
{% endif %}
</span>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
account/views.py:
@login_required
def dashboard(request):
return render(request, 'account/dashboard.html', {'section': 'dashboard'})
структура проекта:
.
├── account
│ ├── static
│ │ └── css
│ │ └── base.css
│ ├── templates
│ │ ├── account
│ │ │ └── dashboard.html
│ │ ├── registration
│ │ │ ├── logged_out.html
│ │ │ ├── login.html
│ │ │ ├── password_change_done.html
│ │ │ ├── password_change_form.html
│ │ │ ├── password_reset_complete.html
│ │ │ ├── password_reset_confirm.html
│ │ │ ├── password_reset_done.html
│ │ │ ├── password_reset_email.html
│ │ │ └── password_reset_form.html
│ │ └── base.html
│ ├── admin.py
│ ├── apps.py
│ ├── forms.py
│ ├── __init__.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── bookmarks
│ ├── asgi.py
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── db.sqlite3
├── manage.py
└── README.md
Ответы (3 шт):
Мне помог такой вариант. Страница выхода не отображается, но разлогинивается.
account/views.py:
from django.contrib.auth import logout
from django.shortcuts import redirect
def logout_view(request):
logout(request)
return redirect('/') # на главную страницу сайта
/account/urls.py:
from django.urls import path, include
urlpatterns += [
path('accounts/logout/', views.logout_view, name='logout'),
path('accounts/', include('django.contrib.auth.urls')),
]
Буквально перехватываешь разлогин и используешь свой метод, а остальные методы из встроенной библиотеки используются.
Я вычитал, что к сожалению в Django 5.0 вообще вырежут LogoutView, а в 4.1 уже считается устаревшим способом разлогина через GET запрос. Подробнее тут.
В книге испоьзуется Django==4.1.0
А ты скорее всего используешь 5.0, где удалили выход из системы по запросу GET
pip3 uninstall Django
pip3 install Django==4.1.0
и должно заработать
Для продолжения в 5 версии Джанго (подсмотрел на странице Django administration) внести в base.css
#logout-form {
display: inline;
}
#logout-form button {
padding: 0;
color: #fff;
background: none;
border: 0;
cursor: pointer;
border-bottom: 1px solid rgba(255, 255, 255, 0.5);
}
и в base.html
<!--<a href="{% url "logout" %}">Log-out</a>-->
<form id="logout-form" action="{% url "logout" %}" method="POST">
{% csrf_token %}
<button type="submit">Log out</button>
</form>]
я тоже читал эту книгу LogoutView не поддерживается Django 5
попробуй этот код должен работать
<form action="{% url 'logout' %}" method="post">
{% csrf_token %}
<button type="submit">Log out</button>
</form>

