0

I want solution for how Django URL work without any optional parameter or with optional parameter.

Here is the URL structure that I want:

path('<slug:category_slug>-comparison/<slug:brand_slug1>-vs-<slug:brand_slug2>-vs-<slug:brand_slug3>/',views.compare_brand)

Now I want something like 1st two slugs for comparison is compulsory so, as per the above URL

path('<slug:category_slug>-comparison/<slug:brand_slug1>-vs-<slug:brand_slug2>',views.compare_brand)

This is working fine because this are compulsory url parameter but I want to pass optional url from 2nd 'vs' to brand_slug3.

Can anyone help me in this?

1 Answer 1

1

You can't do it like this in django urls.py. But you can pass a URL Query string to the view. For example, if you hit this url:

http://localhost:8000/Category1-comparison/Brand1-vs-Brand2/?vs=Brand3

Then you can catch the Brand3 value from request.GET. Like this:

def compare_brand(request, category_slug, brand_slug1, brand_slug2):
     brand_slug3 = request.GET.get('vs')

A better solution:

Maybe a better approach is to use URL query string all together. Because, in that way the url will be much cleaner. For example:

# url

path('/comparison/<slug:category_slug>/', compare_brand)

# view
def compare_brand(request, category_slug):
    brands = request.GET.getlist('brands')
    if len(brands) < 2:
        raise Exception('Need 2 brands atleast')

# browser url
http://localhost:8000/comparison/Cat1/?brands=Brand1,Brand2

From comments

You can create another url pointing to the same view

# url
path('<slug:category_slug>-comparison/<slug:brand_slug1>-vs-<slug:brand_slug2>-vs-<slug:brand_slug3>/',views.compare_brand),
path('<slug:category_slug>-comparison/<slug:brand_slug1>-vs-<slug:brand_slug2>/',views.compare_brand)

# view

def compare_brand(request, category_slug, brand_slug1, brand_slug2, brand_slug3=None):
    if brand_slug3:
       # do something
Sign up to request clarification or add additional context in comments.

4 Comments

No @ruddra actually I don't want like this its break SEO structure.
what if I make another URL path for 3 brand_slug?
@Sahilshaikh yep you can. Please see the #From comments section of the answer
can you answer this question? stackoverflow.com/questions/60375404/…

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.