Django无法呈现注销模板

时间:2016-05-21 14:57:50

标签: python django templates

有以下问题;我通过示例跟随Django,Antonio Mele。这里的练习是设置用户登录和注销。使用默认的contrib.auth视图。当使用书中的代码时。注销视图是管理页面注销的视图;似乎与此处描述的问题相同

django logout redirects me to administration page。尝试过没有成功

我一直在研究这个问题。我的代码现在有效,因为不再呈现管理模板。但是,我仍然无法使用自己的logout.html。我可以重定向到我自己的login.html ...但不是logout.html。注销本身就可以了。用户可以使用模板登录,只能解决此问题。我现在只收到一个浏览器错误

  

页面未正确重定向Iceweasel检测到>服务器正在以一种“从未完成”的方式重定向此地址的请求。此问题有时可能是由于禁用或>拒绝接受cookie造成的

检查cookie可以看到接受csrf令牌

没有可用的追溯没有错误: - (

如果我使用下面的代码,所有工作都有一个例外。我在注销时被重定向到Django Administration注销模板,而不是我自己的logout.html ....这是在书中使用coede时....我自己修改的代码,具有单独的注销功能也无法生成最大递归错误。编辑URLS.PY会停止呈现管理模板。但修改后的代码似乎在网址中存在问题,即.....

这不工作!!!!!

 url(r'^logout/$', 'django.contrib.auth.views.logout',{'next_page': '/account/logout'},  name='logout'),

这完美的工作!!!!

 url(r'^logout/$', 'django.contrib.auth.views.logout',{'next_page': '/account/login'},  name='logout'),

本书的代码如下

FROM BOOK SETTINGS.PY

from django.core.urlresolvers import reverse_lazy

LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')

FROM BOOK VIEWS.PY

from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import LoginForm

@login_required
def dashboard(request):
    return render(request, 'account/dashboard.html', {'section': 'dashboard'})


def user_login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(username=cd['username'], password=cd['password'])
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponse('Authenticated successfully')
                else:
                    return HttpResponse('Disabled account')
            else:
                return HttpResponse('Invalid login')
    else:
        form = LoginForm()
    return render(request, 'account/login.html', {'form': form})

FROM BOOK MAIN URLS.PY

from django.conf.urls import include, url
from django.contrib import admin



urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^account/', include('account.urls')),
    ]

MYAPP(帐号)URLS.PY

from django.conf.urls import url
from . import views


urlpatterns = [
    # url(r'^login/$', views.user_login, name='login'),
    url(r'^$', views.dashboard, name='dashboard'),



    # login / logout urls
    url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
    url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'),
    url(r'^logout-then-login/$', 'django.contrib.auth.views.logout_then_login', name='logout_then_login'),

我修改后的代码

我现在在视图中包含一个单独的注销定义,现在还传递{key_value}对{'next_page':'/ account / logout'}。

如果使用logout def并在urls文件中映射它会在行注销(请求)时生成最大递归错误

def logout(request):
    logout(request)
    request.session.flush()
    request.user = AnonymousUser
    # Redirect to a success page.
    return HttpResponseRedirect(request,'/account/logout.html',context_instance = RequestContext(request))

没有这个def,唯一产生的错误是

“”” 页面未正确重定向

“”“Iceweasel检测到服务器正在以永远无法完成的方式重定向此地址的请求。

This problem can sometimes be caused by disabling or refusing to accept cookies.""""

“”” 我在浏览器中检查了cookie,并看到接受了csrf_token

对我而言,奇怪的是,如果代码:{'next_page':'/ account / logout'}更改为{'next_page':'/ account / login'},一切都会完美无缺。已经尝试了所有发现的建议,不知道任何帮助表示赞赏....

我的代码  VIEWS.PY

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from .forms import LoginForm
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.contrib.auth.models import User


# Create your views here.

@login_required
def dashboard(request):
    return render(request, 'account/dashboard.html',{'section': 'dashboard' })




def user_login(request):
    cd = None
    if request.method=='POST':
        form  = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(username=cd['username'],
                                password=cd['password'])
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponse('Authenticated successfully')
                else:
                    return HttpResponse('Disabled Account')
            else:
                return HttpResponse('Invalid Login')
    else:
        form = LoginForm()
    return render(request, 'account/login.html',{'form': form},context_instance = RequestContext(request))


def logout(request):
    logout(request)
    request.session.flush()
    request.user = AnonymousUser
    # Redirect to a success page.
    return HttpResponseRedirect(request,'/account/logout.html',context_instance = RequestContext(request))

我的代码 帐户/ urls.py

from django.conf.urls import url, patterns
from . import views 



urlpatterns = [
              # post views
              #url(r'^login/$', views.user_login, name='login'),
              # login/logout urls
              url(r'^$', views.dashboard, name='dashboard'),
              url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
              url(r'^logout/$', 'django.contrib.auth.views.logout',{'next_page': '/account/logout'},  name='logout'),
              url(r'^logout-then-login/$','django.contrib.auth.views.logout_then_login', name='logout_then_login'),

              ]

我的代码 MAIN URLS.PY

from django.conf.urls import include, url
from django.contrib import admin


urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^account/', include("account.urls")),
]

mycode的 SETTINGS.PY

LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')

INSTALLED_APPS = (
    'account',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

)

MIDDLEWARE_CLASSES = (
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)


# urlpatterns += patterns('django.contrib.auth.views',
#          #url(r'^login/$', 'login', { 'template_name': 'registration/login.html'}, name='login' ),
#          #url(r'^logout/$', 'logout', { 'template_name': 'registration/logout.html', 'next_page':reverse('index') }, name='logout' ),
#  )

mycode的
logout.html

{% extends "base1.html" %}

{% block title %}Logged Out{% endblock %}


{% block content %}
<h1>
    Logged Out
</h1>
<p>
    You have been successfully logged out. You can <a href="{% url "login" %}">Log-in again</a>
</p>{% endblock %}

mycode的 base1.html

{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}">
</head>
<body>


<div id="header">
    <span class="logo">
        BookMarks
    </span>
{% if 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 %}

{%if user.is_authenticated %}
<span class="user">


Hello {{ user.first_name }} {{ user.last_name }},
<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>

3 个答案:

答案 0 :(得分:4)

您在contrib.auth中使用logout的{​​{1}}视图。此视图会重定向到urls.py指定的网址。您提供'next_page' '/account/logout' - 再次调用next_page视图!

这导致(无限)redirect loop:视图重定向到自身。

请改为:在您自己的logout视图中:

logout

# no redirecting here! return render(request, 'account/logout.html', context_instance=RequestContext(request)) 中为该视图添加网址:

account/urls.py

然后将该网址url(r'^post-logout/$', logout, name='post-logout'), # logout being your own view 提供给实际的('next_page')注销:

auth

答案 1 :(得分:0)

问题的解决方案是按以下方式映射网址

url(r&#39; ^ logout / $&#39;,&#39; django.contrib.auth.views.logout&#39;,{&#39; template_name&#39;:&#39;帐户/logout.html',},name =&#39; logout&#39;),

答案 2 :(得分:0)

我遇到了同样的问题,但后来我一直在阅读

“如果您看到Django管理站点的注销页面而不是您自己的注销页面,请检查项目的INSTALLED_APPS设置,并确保在帐户应用程序之后找到django.contrib.admin。两个模板都是位于相同的相对路径中,Django模板加载器将使用它找到的第一个路径。“