15

As of Django 1.5, you can set LOGIN_URL to a view function name, but I haven't been able to figure out how to specify it correctly.

LOGIN_URL = my_app.views.sign_in

...does not work. I get the error,

ImproperlyConfigured: The SECRET_KEY setting must not be empty.
4

5 回答 5

19

Django 在 django.contrib.auth.views:redirect_to_login 函数中计算这个 url:

resolved_url = resolve_url(login_url or settings.LOGIN_URL)

因此,您应该将其设置为字符串:

LOGIN_URL = 'my_app.views.sign_in'

同样在 settings.py 中,您可以使用 reverse_lazy 函数:

from django.core.urlresolvers import reverse_lazy
LOGIN_URL = reverse_lazy('my_app.views.sign_in')

https://docs.djangoproject.com/en/1.5/ref/urlresolvers/#reverse-lazy

于 2013-08-24T15:47:50.770 回答
5

如果您不想链接LOGIN_URL到“视图”(您可以更改其他),那么您可以链接到中的命名 URL settings.py

from django.core.urlresolvers import reverse_lazy

LOGIN_URL = reverse_lazy('login')

其中“登录”类似于:

url(r'^accounts/login/$', 'my_app.view.Login', name='login'),

然后,如果您更改另一个视图,则无需更改settings.py

于 2014-11-22T05:21:57.987 回答
3

假设您已在 中设置路径名urls.py,则可以将'application_name:view_name'其用作 中的LOGIN_URLsettings.py,如下所示:

应用程序/urls.py

...
path('login/', views.login, name='login'),
...

项目/settings.py

LOGIN_URL = 'application:login'

https://docs.djangoproject.com/en/2.1/ref/settings/#login-url

于 2018-11-06T16:58:03.273 回答
2

Django 2.1.5

django.urls import reverse_lazy
LOGIN_URL = reverse_lazy('namespace of any url used in your project ')
于 2019-02-04T12:39:18.213 回答
0

如果您在项目根目录中有视图(不在应用程序中),您只需在 settings.py 中指定视图名称:

...

LOGIN_URL = 'login'

...

于 2019-09-15T07:03:22.703 回答