python - Django - url 结构

标签 python django url

我应该如何设计 url 或 View 以保持 url 结构如下面的示例所示?

example.com/location/
example.com/category/
example.com/location/category/

url(r'^$', IndexView.as_view(), name='index'),
url(r'^(?P<town>[\w\-_]+)/$', TownView.as_view(), name="town_detail"),
url(r'^(?P<category_slug>[\w\-_]+)/$', CategoryView.as_view(), name="category_list"),

当我尝试访问类别下的 url 时,我被路由到 TownView,这是可以接受的,因为 url 模式几乎相同。

该类别是否应该放在 example.com/c/category/下?

编辑:

我确实按照下面所示的方式解决了我的问题。 所有答案都非常好且有帮助。

我必须验证该解决方案的运作方式并检查它是否会导致任何问题。

url(r'^(?P<slug>[\w\-_]+)/$', BrowseView.as_view(), name="category_list"),
url(r'^(?P<slug>[\w\-_]+)/$', BrowseView.as_view(), name="town_detail"),


class BaseView(ListView):
    queryset = Advert.objects.all().select_related('category', )
    template_name = "adverts/category_view.html"


class BrowseView(BaseView):

    def get_queryset(self, *args, **kwargs):
        qs = super(BrowseView, self).get_queryset(*args, **kwargs)

        try:
            category = Category.objects.get(slug=self.kwargs['slug'])
        except ObjectDoesNotExist:
            object_list = qs.filter(location__slug=self.kwargs['slug'])
        else:
            category_values_list = category.get_descendants(include_self=True).values_list('id', flat=True)
            object_list = qs.filter(category__in=category_values_list)

        return object_list

最佳答案

是的,正则表达式是相同的,Django 采用第一个匹配的,所以你会遇到问题。您可以进行一些调整来区分它们。例如,您推荐的那个很好。为了更加用户友好,您也可以更详细地设计它们,如下所示:

example.com/location/<location name>
example.com/category/<category name>
example.com/location/<location name>/category/<category name>

这样你应该这样做:

url(r'^$', IndexView.as_view(), name='index'),
url(r'^/location/(?P<town>[\w\-_]+)/$', TownView.as_view(), name="town_detail"),
url(r'^/category/(?P<category_slug>[\w\-_]+)/$', CategoryView.as_view(), name="category_list"),
# this one I supposed you'll need for the third one (sort of)
url(r'^/location/(?P<town>[\w\-_]+)/category/(?P<category_slug>[\w\-_]+)/$', Location_CategoryView.as_view(), name="location_category_list"),
...

希望这有帮助!

关于python - Django - url 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16875154/

相关文章:

javascript - 在 WordPress 中,如何将多个变量传递到 URL 并检索它们?

c# - 无需键入其字符串目录即可访问资源文件的 URL

C# 从事件进程中获取事件 url

python - sklearn 问题 : Found arrays with inconsistent numbers of samples when doing regression

C# 如果我有私钥我该如何解密?

python - 从 taggit 获取所有标签

python - 在 Django 中强制执行严格的 SQL 模式

python - Django:clean_ 发生了奇怪的事情

python - 如何在 Keras 中首先通过卷积网络然后通过循环网络传递一对图像?

python - 在 python 中使用捷克字符时的问号