找不到“注销”的反向按钮。 “注销”不是有效的视图函数或模式名称

时间:2019-07-02 14:22:45

标签: html django

Django的新手,并试图通过教程学习如何创建注册页面。尽管完全按照本教程的内容进行操作,但仍遇到此问题。这是我的html,视图和网址。

代码:

<body>
8       <header>
9         <h1>My Site</h1>
10        {% if user.is_authenticated %}
11          <a href="{% url 'logout' %}">logout</a>
12        {% else %}
13          <a href="{% url 'login' %}">login</a> / <a href="{% url 'signup' %}">signup</a>
14        {% endif %}
15        <hr>
16      </header>
17      <main>
18        {% block content %}
19        {% endblock %}
20      </main>
21    </body>

Views.py

from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect

from mysite.core.forms import SignUpForm

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('home')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})

urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.conf.urls import url
from mysite.core import views as core_views


urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
    url(r'^signup/$', core_views.signup, name='signup'),
]

2 个答案:

答案 0 :(得分:1)

您尚未在urls文件中添加注销url,这似乎由一个或多个模板中的url标记所指向。要使其正常工作,您想使用内置的django身份验证,因此您将从django.contrib.auth导入注销,然后将注销URL添加到您的urlpatterns中,如下所示:

from django.contrib.auth import logout #import inbuilt authentication for logging out 

urlpatterns = [
    #then add the url to your url patterns as below
    path('logout', logout, name='logout'),
    url(r'^signup/$', core_views.signup, name='signup'),
]

我遇到了类似的问题,那些步骤对我有用,希望它对您和其他人也有用

答案 1 :(得分:0)

您没有要注销的网址和视图。

您可以这样设置退出网址:

path('logout/user/',views.logout_user,name='logout')

观看次数

from django.contrib.auth import logout

def logout_user(request):
logout(request)
return redirect('redirect where you want')

在模板中也使用request.user代替user,如下所示:

{% if request.user.is_authenticated %}
          <a href="{% url 'logout' %}">logout</a>
       {% else %}
         .................