Reputation: 4054
Is there a way to use only one url for the views to display the content with id(token) and without id(token). For example there is a view which displays the list of profile of user if token is not provided otherwise show a specific user with the token that is passed.
Here is a view
def get(self, request, token=None, format=None):
"""
Returns a list of profile of user or single user if token is provided
"""
reply={}
try:
profile_instance = Profile.objects.filter(user=self.request.user)
if token:
profile = profile_instance.get(token=token)
reply['data'] = self.serializer_class(profile).data
else:
reply['data'] = self.serializer_class(profile_instance, many=True).data
except:
reply['data']=[]
return Response(reply, status.HTTP_200_OK)
The url wil be something like this
url(
r'^users/$',
views.UserList.as_view(),
name="user_list"
),
url(
r'^users/(?P<token>[0-9a-z]+)$',
views.UserList.as_view(),
name="user_profile"
),
Is there a way to have only one url?
Upvotes: 0
Views: 54
Reputation: 12086
Sure, there is a way. Just make the token
url parameter optional. Like this:
url(r'^users/(?P<token>[0-9a-z]+)?$', views.UserList.as_view(), name='user_profile'),
Notice the trailing ?
, which means 0 or 1 matches of the token
. If the token
is provided then it'll be the value provided (obviously!). If not, it will be None
.
Upvotes: 1