0

I have two models - one for tools and one for parts. The list page will be identical. Can I filter what is shown in the template based on URL?

Views (I'd like to combine tool_list and part_list into product_list)

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


def part_list(request):
    parts = Part.objects.all()
    tools = Tool.objects.all()
    return render(request, 'tool_list.html', {'parts': parts, 'tools': tools})


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

url

urlpatterns = [
    url(r'^products/tools/$', tool_list, name='tool_list'),
    url(r'^products/parts-supplies/$', part_list, name='part_list'),
    url(r'^products/(?P<category>[^\.]+)/(?P<slug>[^\.]+)/$', product_detail, name='product_detail'),
]
2
  • Do you want two different urls for a single view? Commented Mar 31, 2016 at 19:42
  • Yes, I want products/tools... and products/parts-supplies... but using the same view template. And, based in the URL, the queryset would be either tools or parts. Now that I think of it, the only way to do this might be to put conditional statements in my template to check for url. Commented Mar 31, 2016 at 20:04

1 Answer 1

1

Your two views, tool_list and part_list are exact replicas of each other. You can create a single view and route multiple urls to it. Like this

def product_list(request):
    tools = Tool.objects.all()
    parts = Part.objects.all()
    return render(request, 'tool_list.html', {'tools': tools, 'parts': parts})

In your urls:

url(r'^products/tools/$', product_list, name='tool_list'),
url(r'^products/parts-supplies/$', product_list, name='part_list'),
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.