Issue
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?
Solution
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.
Answered By - GwynBleidD
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.