Django redirect_authenticated_user:真的不行

时间:2017-09-10 19:38:40

标签: python django django-authentication

我正在Django 1.11中编写应用程序。

myapp/urls.py模式看起来像

from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.views import LoginView

urlpatterns = [
    url(r'^login/$', LoginView.as_view(), {'redirect_authenticated_user': True}),
    url('^', include('django.contrib.auth.urls')),
    url('^', include('pages.urls')),
    url(r'^pages/', include('pages.urls')),
    url(r'^search/', include('search.urls')),
    url(r'^admin/', admin.site.urls),
]

我希望在尝试访问/login页面时重定向登录用户。为此,我按照文档here中的说明将redirect_authenticated_user设置为True

但是,当我成功登录后访问/login时,它不会重定向。

2 个答案:

答案 0 :(得分:7)

redirect_authenticated_user传递给as_view()

urlpatterns = [
    url(r'^login/$', LoginView.as_view(redirect_authenticated_user=True)),
  

传递给as_view()的任何参数都将覆盖在类上设置的属性。在此示例中,我们在TemplateView上设置template_name。类似的重写模式可用于RedirectView上的url属性。

来自Simple usage in your URLconf

答案 1 :(得分:0)

对于使用Django 2调查此问题的任何人,您实际上会使用类似于OP的from flask import Flask from flask_sqlalchemy import SQLAlchemy from datetime import datetime app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) password_hash = db.Column(db.String(128)) posts = db.relationship('Post', lazy='dynamic', back_populates='author') def __repr__(self): return '<User {}>'.format(self.username) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) body = db.Column(db.String(140)) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) author = db.relationship('User') def __repr__(self): return '<Post {}>'.format(self.body) db.drop_all() db.create_all() # Susan will be both created and added to the session u1 = User(username='susan', email='susan@example.com') db.session.add(u1) # John will be created, but not added u2 = User(username='john', email='john@example.com') # Create a post by Susan p1 = Post(body='this is my post!', author=u1) # Add susan's post to the session db.session.add(p1) # Create a post by john, since john does not yet exist as a user, he is created automatically p2 = Post(body='this is my post!', author=u2) # Add john's post to the session db.session.add(p2) # After the session has everything defined, commit it to the database db.session.commit()

kwargs

https://docs.djangoproject.com/en/2.0/topics/http/urls/#views-extra-options