Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass uuid to reverse() to construct url

I have a url:

url(r'^profile_detail/(?P<uuid>%s)/$' % uuid, ProfileDetailView.as_view(), name="profile_detail_view")

And I need to redirect a user to that view, but I don't know how to construct the url without hardcoding it, which I don't want to do.

I figured something like:

reverse('profile_detail_view' 'profile.uuid')

And I tried some variations of that, but I didn't get it right. I also tried something with args and kwargs, but nothing.

How do I do it?

like image 967
dnmh Avatar asked Mar 16 '23 07:03

dnmh


1 Answers

urls.py
In urls.py you only define patterns that – when matched – call the given view. What has been matched will be passed to the view as named argument, e.g.

url(
    r'^profile_detail/(?P<uuid>[\d\-]+)/$', 
    ProfileDetailView.as_view(), 
    name="profile_detail_view"
)

This pattern will match digits (0-9) and the hyphen (-) (depending on the uuid you can strengthen the regex in terms of grouping and length).

view
It is then the responsibility of your view to look up the user that this uuid belongs to (or raise an error if no user was found), e.g.

class ProfileDetailView(View):
    def get(self, request, uuid):
        try:
            user = User.objects.get(uuid=uuid)
        except User.DoesNotExist:
            raise Http404  # or whatever else is appropriate

        # ...

reversing
Reversing the view works by passing everything necessary to the reverse function. The key in kwargs needs to match the named regex in your url pattern (?P<uuid>[\d\-]+)

reverse('profile_detail_view', kwargs={'uuid': profile.uuid})
like image 178
sthzg Avatar answered Mar 19 '23 17:03

sthzg