Pergunta

I have the following views:

def tag_page(request, tag):

    products = Product.objects.filter(tag=tag)

    return render(request, 'shop/tag_page.html', {'products': products, 'tag': tag})


def product_page(request, slug):

    product = Product.objects.get(slug=slug)

    return render(request, 'shop/product_page.html', {'product': product})

along with the following url configurations:

url(r'^(?P<tag>.+)/$', 'tag_page'),
url(r'^(?P<tag>.+)/(?P<slug>[-\w]+)/$', 'product_page'),

The regex that has "tag" in it allows a url path to grow arbitrarily while sort of circularly redirecting to the tag_page view.

This lets me have the url: /mens/shirts/buttonups/, where all sections (/mens, /mens/shirts, /mens/shirts/buttonups/) of the path direct to the tag_page view, which is desired.

I want to end this behavior at some point however, and direct to a product_page view, which I attempt to accomplish with:

url(r'^(?P<tag>.+)/(?P<slug>[-\w]+)/$', 'product_page'),

When I follow a product_page link:

<a href="{{ product.slug }}">{{ product }}</a>

I am directed to the tag_pag view. Presumably because that slug url matches the tag regex.

So the question: Is there a way I can keep the flexible tag regex redirect behavior but then "break" from it once I reach a product page? One important thing to note is that I want to keep the product page within the built up url scheme like: mens/shirts/buttonups/shirt-product/

Any insight is appreciated, Thanks!

Foi útil?

Solução

Do you really need the forward slash on the end of the product page URL? A URL which ends with a forward slash is distinct from one which does not.

Just like delimiters are left at the end of a path to suggest a directory (with files underneath it) and left off at the end of file paths, so too could you leave the slash on for the tag sections but lop it off for individual products.

That gets around the problem entirely :-)

Outras dicas

I think that you can't do it with just urlconf- .* always matches everything. I would do that in this way:

url(r'^(?P<path>.+)/$', 'path_page'),

def path_page(request,path):
    tags,unknown = path.rsplit('/',1)
    try:
        product = Product.objects.get(slug=unknown)
        return some_view_function(request,path,product)
    except Product.DoesNotExist:
        return some_another_view_function(request,path)

But- I see here a few problems:

  • What if tag has the same name as product's slug?
  • Your solution is SEO unfriendly unless you want to bother with duplicate content meta tags
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top