What is @permalink and get_absolute_url in Django?

前端 未结 4 2029
走了就别回头了
走了就别回头了 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:21

    As of 2013, the Django documentation discouraged use of the permalink decorator and encouraged use of reverse() in the body of the get_absolute_url method. By 2015, the permalink decorator seemed to have vanished without a trace from the Django documentation, and it was finally removed in Django version 2.1 in 2018.

    So, for a standard DRY way to create a permanent link to a single object view, use get_absolute_url() in your model like this:

    from django.db import models
    from django.urls import reverse
    #  NOTE: pre Django 1.10+ this is "from django.core.urlresolvers import reverse"
    
    
    class MyModel(models.Model):
        slug = models.SlugField()
    
        def get_absolute_url(self):
            return reverse('mymodel_detail', args=(self.slug,))
    

    and then have an entry in urls.py that points to your view:

    url(r'^(?P[-\w\d\_]+)/$',
        MyModelDetailView.as_view(),
        name='mymodel_detail'),
    

提交回复
热议问题