我正在做一个课程练习而且我被困了几个小时而且我不确定是什么导致应用程序崩溃,接下来,你会发现所涉及的文件,也许你可以找到解决方案。谢谢你的帮助!
登录时抛出此错误:
Internal Server Error: /account/login/
...
django.urls.exceptions.NoReverseMatch: Reverse for 'dashboard' not found. 'dashboard' is not a valid view function or pattern name.
[04/Apr/2018 17:12:15] "POST /account/login/ HTTP/1.1" 500 151978
settings.py 文件的末尾
from django.urls import reverse_lazy
LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_REDIRECT_URL = reverse_lazy('logout')
urls.py 文件
from django.contrib.auth import views as auth_views
from django.urls import path
from . import views
app_name = 'account'
urlpatterns = [
# path('login/', views.user_login, name='login'),
path('', views.dashboard, name='dashboard'),
# login / logout urls
path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'),
path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'),
]
views.py 文件
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render
@login_required
def dashboard(request):
return render(request, 'account/dashboard.html', {'section': 'dashboard'})
base.html 模板
{% load staticfiles %}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{% static "css/base.css" %}">
</head>
<body>
<div id="header">
<span class="logo">Bookmarks</span>
{% if request.user.is_authenticated %}
<ul class="menu">
<li> {% if section == "dashboard" %}class="selected"{% endif %}><a href="{% url "account: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 }}, <a href="{% url "account:logout %}">Logout</a>
{% else %}
<a href="{% url "account:dashboard" %}"></a>
{% endif %}
</span>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
感谢您的帮助。非常感谢!
答案 0 :(得分:10)
您已为网址设置了命名空间:
app_name = 'account'
在使用reverse
/ reverse_lazy
或{% url %}
撤消网址时,您需要使用该命名空间:
LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard')
LOGIN_URL = reverse_lazy('account:login')
LOGOUT_REDIRECT_URL = reverse_lazy('account:logout')
答案 1 :(得分:1)
也许在指定{%url'appname:views'%}时您指定了错误的应用程序名称
例如,像
wrong - {% url 'accuant:dashboard' %}
right - {% url 'account:dashboard' %}