【问题标题】:How to make unique urls in django with url-pattern that uses multiple parameters?如何使用使用多个参数的 url-pattern 在 django 中制作唯一的 url?
【发布时间】:2018-10-29 03:27:06
【问题描述】:

我的网址是这样构成的:

example.com/category/subcategory/name

现在我正在使用 DetailView,它会在我编写它时检测到 url,但它会积极解析为包含正确名称的任何地址,因为该名称是唯一的,所以我需要检查的是该名称是否对应于子类别,并且此子类别对应于主类别。

例如我想要的网址是:

http://example.com/animal/cat/garfield

它可以通过 200 代码解析。 但是,当我写:

http://example.com/insect/cat/garfield

它也解析为 200 而不是 404。

如何在我的视图中检查这些参数?

我的 urls.py

path('<str:category>/<str:subcategory>/<str:slug>', views.AnimalDetailView.as_view(), name="animal_detail") 

我的看法:

class AnimalDetailView(DetailView):
    model = Animal

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['now'] = timezone.now()
        return context

【问题讨论】:

    标签: django url-pattern


    【解决方案1】:

    您可以做的是,在get_object 方法中,通过覆盖它来设置自己的约束。例如:

    class AnimalDetailView(DetailView):
         ...
         def get_object(self):
             category = self.kwargs.get('category')
             subcategory = self.kwargs.get('subcategory')
             slug = self.kwargs.get('slug')
             animal = Animal.objects.filter(category=category, subcategory=subcategory, slug=slug)
             if animal.exists():
                  return super(AnimalDetailView, self).get_object()
             else: 
                  Http404("Animal not found")
    

    【讨论】:

    • 它抛出一个 ValueError,它试图将这个词与一个 int 值进行比较。
    • 写作 category__slug 它似乎可以工作,但是当它没有找到任何东西时,它仍然会得到一个对象,因此它永远不会抛出 404,而是一个空视图。
    • 意味着你在某处有一个 /insect/cat/garfield 的 Animal 对象。可以分享一下您的类别、子类别和动物模型吗?
    【解决方案2】:

    我认为您的网址应该以/ 结尾。参考https://docs.djangoproject.com/en/2.1/topics/http/urls/

    path('<str:category>/<str:subcategory>/<str:slug>/', views.AnimalDetailView.as_view(), name="animal_detail").
    

    通过 URL 传递的所有参数都将使用 kwargs 获取。如果您想在视图中访问参数,可以使用以下方法 1)

    class Test(DetailView):
        def get(self, request, **kwargs):
            subcategory = kwargs['subcategory']
            category = kwargs['category']
    

    2)

    class Test(DetailView):
        def get(self, request, category, subcategory, .. ):
            # category contains value of category
    

    第一种方法是首选方法。

    【讨论】:

    • 谢谢,但这不是我的问题。
    • 你能发布完整的 URLs.py。因为一切看起来都很好,应该可以工作!
    • 我想要的是能够处理该通用视图中的所有三个 url 参数,以便只有一个有效的 url。
    猜你喜欢
    • 2016-12-27
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 2013-02-03
    • 2017-11-14
    • 2016-11-07
    • 2010-12-02
    • 1970-01-01
    相关资源
    最近更新 更多