如何在Django模板中使用域get_absolute_url?

Dee*_*eep 4 django

所以我有点挣扎,有些东西在逻辑上看起来很简单,但由于我对Django的理解有限,我不知道在哪里看以及如何制定解决方案.

基本上我有一个博客应用程序设置,它显示主页上的完整(所有内容,包括disqus讨论)最新帖子.该帖子还有一个链接到帖子自己的页面.我已经设置了Disqus并需要获取一些关键信息用于disqus_urldisqus_identifier.我已经按如下方法设置了如下模型get_absolute_url:

def get_absolute_url(self):
    return reverse('blog.views.renderBlog',args=[str(self.id),str(self.slug)])
Run Code Online (Sandbox Code Playgroud)

我的观点设置如下:

def renderBlog(request,postid=1,slug=None):
    template = 'blog_home.html'

    if(postid == 1 and slug == None):
        post = Post.objects.latest('date_created')
    else:
        post = Post.objects.get(slug=slug, id=postid)

    data = {
            'post':post,
        }

    return render(request, template, data)
Run Code Online (Sandbox Code Playgroud)

如您所见,视图设置为处理两个URL,如下所示:

    url(r'^$', 'renderBlog', name='blogHome'),
    url(r'^post/(?P<postid>\d{1,4})/(?P<slug>[\w-]+)/$', 'renderBlog', name='blogPostPage'),
Run Code Online (Sandbox Code Playgroud)

在我的模板中,我正在设置,disqus_identifier = '{{ post.get_absolute_url }}'同时我正在硬编码域部分disqus_url = 'http://127.0.0.1{{ post.get_absolute_url }}';..评论计数也是如此<a href="" data-disqus-identifier.

我不喜欢以一种黑客的方式做事,这对我来说是最好的方法来获得完整的绝对网址.我查看了request.get_absolute_uri但我不确定如何实际使用它来获得我想要的东西.

谢谢

leh*_*ins 9

我喜欢这样做的方法是配置一个context_processor:

from django.contrib.sites.models import Site

def base_context_processor(request):
     return {
         'BASE_URL': "http://%s" % Site.objects.get_current().domain
     }
     # or if you don't want to use 'sites' app
     return {
         'BASE_URL': request.build_absolute_uri("/").rstrip("/")
     }
Run Code Online (Sandbox Code Playgroud)

settings.py:

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'path.to.base_context_processor',
    ...
)      
Run Code Online (Sandbox Code Playgroud)

(在较新版本的Django中,修改context_processorsTEMPLATES,OPTIONS而不是.)

然后在模板中:

<a href="{{ BASE_URL }}{{ obj.get_absolute_url }}">Object Name</a> 
Run Code Online (Sandbox Code Playgroud)

另一个解决方案是使用request.build_absolute_uri(location),但是你必须创建一个模板标签,它接受一个request对象和一个location具有get_absolute_uri方法的对象.然后你就可以使用它那样的模板:{% get_full_uri request=request obj=post %}.以下是有关如何编写自定义标记的文档.

  • 请注意,此"BASE_URL"不适用于https站点或具有端口组件的URL.最好使用`"BASE_URL":request.build_absolute_uri("/").rstrip("/")`,它将正确处理所有这些情况. (4认同)