使用基于类的视图时,在Django中获取绝对URL

时间:2021-11-05 19:18:10

Hello I am migrating my app to use class based views instead of function based views. In my old code I was able to get the absolute URL of an object related to a function view this way:

您好我正在迁移我的应用程序以使用基于类的视图而不是基于函数的视图。在我的旧代码中,我能够以这种方式获取与函数视图相关的对象的绝对URL:

class Category(models.Model):
    name = models.CharField(max_length=100,unique=True)
    slug = models.SlugField(unique=True)
    description = models.TextField()
    parent = models.ForeignKey('self',null=True,blank=True)

    def get_absolute_url(self):
        return reverse('blog.views.showcategory',args=[str(self.slug)])

I couldn't find what I should change in my get absolute url function in order to get the same result.

我无法在我的获取绝对url函数中找到我应该更改的内容以获得相同的结果。

This is my new class based view

这是我基于班级的新视图

class CategoryView(ListPosts):
    template_name = "postlist.html"
    context_object_name="posts"
    def get_queryset(self):
         return Post.objects.filter(category__slug=self.kwargs['slug']).order_by('created')

Thanks!

5 个解决方案

#1


19  

You should always give your URLs a name, and refer to that:

您应始终为您的网址命名,并参考:

url(r'/category/(?P<slug>\w+)/$', CategoryView.as_view(), name='category_view'),

Now:

@models.permalink
def get_absolute_url(self):
    return ('category_view', (), {'slug': self.slug})

Note I've used the permalink decorator, which does the same as calling reverse but is a bit neater.

注意我已经使用了永久链接装饰器,它与调用反向操作相同,但有点整洁。

#2


9  

Here is my get_absolute_url configuration:

这是我的get_absolute_url配置:

urls.py

urlpatterns = patterns('',
    url(r'^products/(?P<slug>[\w\d\-\_]+)/$', views.ProductView.as_view(), name='product'),
    )

models.py

def get_absolute_url(self):
    return reverse('products:product', kwargs={'slug':self.slug})

My urls.py is under the "products" app, so the url namespace is "products:product"

我的urls.py位于“products”应用程序下,因此url名称空间为“products:product”

#3


0  

This function worked for me, it uses multiple parameters:

这个功能对我有用,它使用多个参数:

def get_absolute_url(self):
return reverse('video', kwargs={'slug':self.chapiter.course.slug,'chpiter_slug':self.chapiter.chpiterSlug,'pk':str(self.index).zfill(2)})

#4


0  

Here is how you do it in Django >= 2.0.

这是你在Django> = 2.0中的表现。

In urls.py

from django.urls import path

app_name = 'my_app'

urlpatterns = [
    path('products/<slug:slug>', views.ProductDetailView.as_view(), name='products')
]

Add the following code to your models.py

将以下代码添加到models.py中

class Product(models.Model):
    name = models.CharField(max_length=125)
    slug = models.SlugField(unique=True)
    # rest of the fields

   def get_absolute_url(self):
         return reverse('my_app:products', kwargs={'slug': self.slug})

For displaying the detail, add a generic view in your views.py

要显示详细信息,请在views.py中添加通用视图

class ProductDetailView(DetailView):
     template_name = 'my_app/detail.html'

     def get_queryset(self):
         return Product.objects.all()

#5


0  

The 2018 answer to this question is basically the same as @Aaron's, but for quick access here it is:

这个问题的2018答案与@ Aaron的答案基本相同,但为了快速访问,它是:

def get_absolute_url(self):
    from django.urls import reverse
    return reverse('people.views.details', args=[str(self.id)])

From https://docs.djangoproject.com/en/2.1/ref/models/instances/#get-absolute-url

#1


19  

You should always give your URLs a name, and refer to that:

您应始终为您的网址命名,并参考:

url(r'/category/(?P<slug>\w+)/$', CategoryView.as_view(), name='category_view'),

Now:

@models.permalink
def get_absolute_url(self):
    return ('category_view', (), {'slug': self.slug})

Note I've used the permalink decorator, which does the same as calling reverse but is a bit neater.

注意我已经使用了永久链接装饰器,它与调用反向操作相同,但有点整洁。

#2


9  

Here is my get_absolute_url configuration:

这是我的get_absolute_url配置:

urls.py

urlpatterns = patterns('',
    url(r'^products/(?P<slug>[\w\d\-\_]+)/$', views.ProductView.as_view(), name='product'),
    )

models.py

def get_absolute_url(self):
    return reverse('products:product', kwargs={'slug':self.slug})

My urls.py is under the "products" app, so the url namespace is "products:product"

我的urls.py位于“products”应用程序下,因此url名称空间为“products:product”

#3


0  

This function worked for me, it uses multiple parameters:

这个功能对我有用,它使用多个参数:

def get_absolute_url(self):
return reverse('video', kwargs={'slug':self.chapiter.course.slug,'chpiter_slug':self.chapiter.chpiterSlug,'pk':str(self.index).zfill(2)})

#4


0  

Here is how you do it in Django >= 2.0.

这是你在Django> = 2.0中的表现。

In urls.py

from django.urls import path

app_name = 'my_app'

urlpatterns = [
    path('products/<slug:slug>', views.ProductDetailView.as_view(), name='products')
]

Add the following code to your models.py

将以下代码添加到models.py中

class Product(models.Model):
    name = models.CharField(max_length=125)
    slug = models.SlugField(unique=True)
    # rest of the fields

   def get_absolute_url(self):
         return reverse('my_app:products', kwargs={'slug': self.slug})

For displaying the detail, add a generic view in your views.py

要显示详细信息,请在views.py中添加通用视图

class ProductDetailView(DetailView):
     template_name = 'my_app/detail.html'

     def get_queryset(self):
         return Product.objects.all()

#5


0  

The 2018 answer to this question is basically the same as @Aaron's, but for quick access here it is:

这个问题的2018答案与@ Aaron的答案基本相同,但为了快速访问,它是:

def get_absolute_url(self):
    from django.urls import reverse
    return reverse('people.views.details', args=[str(self.id)])

From https://docs.djangoproject.com/en/2.1/ref/models/instances/#get-absolute-url