冲突的Django URL

时间:2016-04-16 22:18:13

标签: django django-models django-templates django-views

我已经在这里剁了几天而不知道为什么它不起作用。我有两个视图,一个列出工具,一个列出部件。我还有两个列表和详细信息URL。两个列表视图都有效,工具详细信息视图也可以工作,但是当我点击一个零件项目来查看详细信息时,浏览器中会显示正确的URL,但是我在下面的屏幕截图中显示了一个错误,正如您所看到的那样使用tool_detail视图。谢谢你的期待。

enter image description here

以下是我的审核代码:

URL:

from .views import tool_list, part_list, tool_detail, part_detail

urlpatterns = [

    url(r'^products/tools/$', tool_list, name='tool_list'),
    url(r'^products/(?P<category>[^\.]+)/(?P<slug>[^\.]+)/$', tool_detail, name='tool_detail'),

    url(r'^products/parts/$', part_list, name='part_list'),
    url(r'^products/(?P<category>[^\.]+)/(?P<slug>[^\.]+)/$', part_detail, name='part_detail'),

]

查看:

def tool_list(request):
    tools = Tool.objects.prefetch_related('uploads').all()
    return render(request, 'tool_list.html', {'tools': tools})


def tool_detail(request, **kwargs):
    tool = get_object_or_404(Tool, slug=kwargs.get('slug'))
    return render(request, 'tool_detail.html', {'tool': tool})


def part_list(request):
    parts = Part.objects.prefetch_related('uploads').all()
    return render(request, 'part_list.html', {'parts': parts})


def part_detail(request, **kwargs):
    part = get_object_or_404(Part, slug=kwargs.get('slug'))
    return render(request, 'part_detail.html', {'part': part})

模型

class Part(Timestamp):
    model_number = models.ForeignKey(ModelNumber, related_name='part_model_number')
    category = models.ForeignKey(Category, related_name='part_category')
    price = models.DecimalField(max_digits=10, decimal_places=2)
    title = models.CharField(max_length=250)
    slug = models.SlugField(help_text="slug-title-should-be-like-this")
    ...

class Tool(Timestamp):
    model_number = models.ForeignKey(ModelNumber, related_name='tool_model_number')
    price = models.DecimalField(max_digits=10, decimal_places=2)
    title = models.CharField(max_length=250)
    slug = models.SlugField(help_text="slug-title-should-be-like-this")
    category = models.ForeignKey(Category, related_name='tool_category')
    ...

1 个答案:

答案 0 :(得分:1)

匹配的第一个url模式是Django将用于调度到视图的内容。第二个网址匹配,因此使用tool_detail视图。