In my Django website, I have a certain parameter that I would like to set through url, or query string. E.g. mysite.com/?param=value. I want this value to be passed to all the views once it has been set – I can check it with request.GET.get('param', 'default value'). What would be the easiest way to do that in Django?
To make it more clear, here is an example – in the header of my site I have a dropdown menu with a list of years. Once I click on one of the choices I want this year to be carried over to all the other other parts of my website, i.e. mysite.com/?year=1999, then mysite.com/somethingelse/?year=1999, mysite.com/onemorething/?year=1999 and so on.
Thanks in advance.
One choice is to store this in
request.sessionrather than inrequest.GET. It would still be set and accessed just as you would want it to be:See here for all the details of using sessions.
The exception would be if you specifically want this in the URL so that it is transparent and the user can change it.
ETA: Some answers to your questions:
If you really want a ?year=1999 URL to set the session variable in any view, you could create a custom middleware class. Middleware serves as a filter that can alter an HttpRequest before it reaches the view, or alter the HttpResponse that is returning from the view. In this case, you can have it check request.GET and set request.session if necessary, before it then executes the view. See the docs and be sure to read the details about middleware.
Having it in the URL is just not a good idea. There are ways around it but they’re a lot of trouble.
You can use RequestContext to pass a request to a template to be modified there. But why on earth would you do it there instead of in the view function?