What is @permalink and get_absolute_url in Django?

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

    A better approach is to declare a name for your app in urls.py and then refer to that instead of hard coding anything:

    in urls.py:

    app_name = 'my_app'
    
    urlpatterns = [
        path('blogs/', blog.views.blog_detail, name='mymodel_detail'),
        ]
    
    

    and in models.py:

    from django.urls import reverse
    
    
    class BlogPost(models.Model):
        name = modelsCharField()
        slug = models.SlugField(...)
    
        def get_absolute_url(self):
            return ('my_app:mymodel_detail, args=[self.slug,])
    

提交回复
热议问题