可以在django中给出外部URL名称 [英] Is it possible to give external URLs names in django

查看:231
本文介绍了可以在django中给出外部URL名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始在Django中命名我的URL模式,所以如果我想改变URL模式,我只需要在一个地方改变它。例如:

  url(r'^ $',HomeListView.as_view(),name ='home'),

在我的模板中引用它,如下所示:

  {%url home%} 

这可能与外部链接以防万一他们改变了,或者我改变了一个Facebook页面链接。这个样子怎么样?



谢谢

解决方案

这可能是写一个external_url模板标签,并且有一个ExternalURL模型存储它们。



这将给你的优势是可以让urls可编辑而不重新部署更改代码。



缺点是会有数据库查找来查看这些URL。另外,您需要在



<$ p $中的 c> {%load external_urls%} p> #models.py伪代码

class ExternalURL(models.Model):
name = models.CharField(unique = True)
url = models.URLField()

您的模板标签可能如下所示:

 #app / templatetags / external_url.py 

@ library.register()
def external_url(name):
try:
return ExternalURL.objects.get(name = name).url
except ExternalURL.DoesNotExist:
return''
/ pre>

另一个替代方案可能是有一个上下文处理器将它们全部存储在上下文中,允许您不必将它们明确地传递到视图中:如果你有几个外部URL在你的系统中的许多地方使用。

  def external_urls(request):
return {
'google :'http://www.google.com/',
#more here
}

这样做的优点是没有数据库查找,不需要加载模板标签,但是您需要将其添加到您的 settings.CONTEXT_PROCESSORS 中。此外,您可以检查请求以查看当前用户是否可以看到所有的URL。


I have just started naming my URL patterns in Django, so that if I want to change the URL pattern, I just have to change it in one place. e.g:

url(r'^$', HomeListView.as_view(), name='home'),

And referencing it in my templates like this:

{% url home %}

Is this possible with external links in case they change or I change the a Facebook page link for example. How would this look?

Thanks

解决方案

One way to do this could be to write an external_url template tag, and have an ExternalURL model that stores them.

This would give you the advantage of being able to have the urls editable without redeploying changed code.

The disadvantage is that there will be database lookups to see those urls. Also, you would need to {% load external_urls %} in templates you want to use it in.

# models.py pseudo-code

class ExternalURL(models.Model):
    name = models.CharField(unique=True)
    url = models.URLField()

Your template tag might look something like:

# app/templatetags/external_url.py

@library.register()
def external_url(name):
    try:
        return ExternalURL.objects.get(name=name).url
    except ExternalURL.DoesNotExist:
        return ''

Another alternative could be to have a Context Processor that stores them all in the context, allowing you to not have to pass them explicitly into views: would be useful if you had several external urls that were used in many places within your system.

def external_urls(request):
    return {
        'google': 'http://www.google.com/',
        # more here
    }

The advantages of this is no database lookup, no requirement to load the template tag, but you will need to add it to your settings.CONTEXT_PROCESSORS. Also, you could inspect request to see if the current user may see all the urls.

这篇关于可以在django中给出外部URL名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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