Login

Persistent Params Decorator

Author:
achimnol
Posted:
August 6, 2009
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

This snippet helps preserving query parameters such as page number when the view perform redirects.

It does not support hooking templates and contexts currently.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def persistent_params(*param_names):
    def decorate(view_func):
        @wraps(view_func)
        def decorated(request, *args, **kwargs):
            response = view_func(request, *args, **kwargs)
            if response.status_code in (301, 302, 303, 307):
                location = response['Location']
                parts = location.split('?')
                if len(parts) == 1:
                    query_dict = QueryDict('', mutable=True)
                else:
                    query_dict = QueryDict(parts[1], mutable=True)
                for name in param_names:
                    query_dict[name] = request.GET.get(name, None)
                new_query_string = query_dict.urlencode()
                response['Location'] = parts[0] + '?' + new_query_string
            return response
        return decorated
    return decorate

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

ssadler (on August 6, 2009):

I think I'd change line 6 to be more explicit, ie:

if response.status_code in (301, 302, 303, 307):

To be safe.

#

achimnol (on September 12, 2009):

Thanks ssadler for pointing it. :)

#

Please login first before commenting.