我应该如何设计 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/