Jim
Jim

Reputation: 14280

How to tell a Django view who called it?

I have two Django views that render two separate templates. Each of these templates will contain a link to the same third view.

That third view will render a template that should display one button if the first Django view/template link redirected to it but render a different button if the second view/template link redirected to it. The URI for the link in each of these templates will be something like this:

/members/near/<from_uid>/profile/<to_uid>/

What is the most robust or "best-practice" way to tell the third view who called it? Should I create links like the following?

/members/near/<from_uid>/profile/<to_uid>/from/<view_name>
/members/near/<from_uid>/profile/<to_uid>/from/<view_name>

Would it be better to examine the HTTP referer header field in the request? Or is there some other better technique for doing this?

By the way, I realize my URI isn't RESTful but I don't feel that I understand REST sufficiently well to create RESTful URIs, particularly when I have to pass multiple arguments as I do here with the from_uid and to_uid arguments.

Thanks!

Upvotes: 0

Views: 72

Answers (2)

ejb
ejb

Reputation: 304

Use GET parameters like this...

Template 1:
<a href="/third/view/?from=view1">Link</a>

Template 2:
<a href="/third/view/?from=view2">Link</a>

And in your third view...
from_view = self.request.GET.pop('from') if from_view == 'view1': ... elif from_view == 'view2': ...

GET parameters are more appropriate than URL-captured parameters in a situation like this.

Upvotes: 0

Othman
Othman

Reputation: 3018

You can have a part of the URL to be used as a parameters. Each parameter will be set based on the regex provided. an example here. One view can handle all your urls that contain the three parameters you mentioned.

url(r'^members/near/(?P<from_uid>\d+)/profile/(?P<to_uid>\d+)/from//(?P<view_name>\W+)/$', MyView.as_view(), name = 'my_named_view')

Then in your view you just pull these parameters from the url

from_uid = self.kwargs['from_uid']
to_uid = self.kwargs['to_uid']
view_name = self.kwargs['view_name']

if view_name == "....":
    # render to template1
elif view_name == "....":
    # render to template2

Upvotes: 1

Related Questions