Home > Back-end >  Different URL Based On Condition In Django
Different URL Based On Condition In Django

Time:10-01

I have a url like this:

app_name = 'vineyards'
urlpatterns = [
    path('<str:parent>/<str:region>/<slug:slug>/',
         vineyard_detail, name="detail"),
]

This is the absolute url in model:

def get_absolute_url(self):
    return reverse('vineyards:detail', kwargs={'parent': self.region.region_parent, 'region': self.region.slug, 'slug': self.slug})

The <str:parent>/ is optional, it can be null. I want to ignore the <str:parent>/ if it is None

So for example, i want the url is something like this: .../something/

Instead of this : .../None/something/

How can i do that? Is it possible?

CodePudding user response:

The simplest solution would be to add a second path to your URL patterns:

app_name = 'vineyards'

urlpatterns = [
    path('<str:parent>/<str:region>/<slug:slug>/',
         vineyard_detail, name="detail"),
    path('<str:region>/<slug:slug>/',
         vineyard_detail, name="detail-without-parent"),
]

And then use the second path in the get_absolute_url method, when there is no parent defined:

def get_absolute_url(self):
    if self.region.region_parent is not None:
        return reverse('vineyards:detail', kwargs={'parent': self.region.region_parent, 'region': self.region.slug, 'slug': self.slug})
    else:
        return reverse('vineyards:detail-without-parent', kwargs={'region': self.region.slug, 'slug': self.slug})

But from what you have here, it looks like your are trying to create some tree structure. Maybe consider using something like django-mptt for that.

CodePudding user response:

It is possible to get what you need creating two patterns (please pay attention to the order)

urlpatterns = [
    path('<str:region>/<slug:slug>/', vineyard_detail, name="detail_no_parent"),
    path('<str:parent>/<str:region>/<slug:slug>/', vineyard_detail, name="detail"),
]

and then make sure that the parent value is optional in the view (you can do it setting up a default value)

def vineyard_detail(request, slug, region, parent=None):
    pass
  • Related