What is @permalink and get_absolute_url in Django?

前端 未结 4 2067
走了就别回头了
走了就别回头了 2021-01-30 09:02

What is @permalink and get_absolute_url in Django? When and why to use it?

Please a very simple example (a real practical exam

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-30 09:40

    @permalink is a python decorator, while get_absolute_url is a method on a django model.

    Both are concerned with allowing you to reverse the URL for a particular object and should be used together. They are used anytime you need to provide a link to a particular object or want to display that object's specific URL (if it has one) to the user

    You could simply write your get_absolute_url method to return a hard coded string, but this wouldn't adhere to Django's philosophy of DRY (don't repeat yourself). Instead, there is the @permalink to make things more flexible.

    If you read the docs on the subject you will see how they relate to each other. the @permalink decorator hooks into django's URLconf's backend, allowing you to write much more portable code by using named url patterns. This is preferable to just using get_absolute_url on it's own: your code becomes much DRYer as you don't have to specify paths.

    class BlogPost(models.Model):
        name = modelsCharField()
        slug = models.SlugField(...)
    
        @permalink
        def get_absolute_url(self):
            return ("blog-detail", [self.slug,])
    

    and in urls.py

        ...
        url(r'/blog/(?P[-w]+)/$', blog.views.blog_detail, name="blog-detail")
    

提交回复
热议问题