Django - 在设置中使用反向网址映射 [英] Django - use reverse url mapping in settings

查看:162
本文介绍了Django - 在设置中使用反向网址映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

django设置文件中的几个选项是url,例如 LOGIN_URL LOGIN_REDIRECT_URL 。可以避免对这些url进行硬编码,而是使用反向网址映射?在这一刻,这真的是我发现自己在多个地方写同一个URL的唯一的地方。

A few of the options in the django settings file are urls, for example LOGIN_URL and LOGIN_REDIRECT_URL. Is it possible to avoid hardcoding these urls, and instead use reverse url mapping? At the moment this is really the only place where I find myself writing the same urls in multiple places.

推荐答案

Django 1.5及更高版本



从Django 1.5开始, LOGIN_URL LOGIN_REDIRECT_URL 接受命名的URL模式。这意味着您不需要在设置中对任何URL进行硬编码。

Django 1.5 and later

As of Django 1.5, LOGIN_URL and LOGIN_REDIRECT_URL accept named URL patterns. That means you don't need to hardcode any urls in your settings.

LOGIN_URL = 'login' # name of url pattern

对于Django 1.5 - 1.9,您还可以使用视图功能名称,但在Django 1.10中已被弃用所以不推荐。

For Django 1.5 - 1.9, you can also use the view function name, but this is deprecated in Django 1.10 so it's not recommended.

LOGIN_URL = 'django.contrib.auth.views.login' # path to view function



Django 1.4



对于Django 1.4,你可以使用 reverse_lazy

LOGIN_URL = reverse_lazy('login')



Django 1.3及更早版本



这是原来的答案,它在 reverse_lazy 添加到Django

Django 1.3 and earlier

This is the original answer, which worked before reverse_lazy was added to Django

在urls.py中,导入设置:

In urls.py, import settings:

from django.conf import settings

然后添加url模式

urlpatterns=('',
    ...
    url('^%s$' %settings.LOGIN_URL[1:], 'django.contrib.auth.views.login', 
        name="login")
    ...
)

请注意,您需要切片 LOGIN_URL 删除前导正斜杠。

Note that you need to slice LOGIN_URL to remove the leading forward slash.

在shell中:

>>>from django.core.urlresolvers import reverse
>>>reverse('login')
'/accounts/login/'

这篇关于Django - 在设置中使用反向网址映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆