DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Django: Sticky URL Query Parameters per View

Django: Sticky URL Query Parameters per View

Chase Seibert user avatar by
Chase Seibert
·
Feb. 22, 12 · Web Dev Zone · Interview
Like (0)
Save
Tweet
5.44K Views

Join the DZone community and get the full member experience.

Join For Free

On pages that contain filter controls, such as search results pages, it's common for the filter selections to be put into the URL using query parameters. This makes the search results bookmark-able. A common requirement on such pages is to have the application remember the particular filter parameters the user set the last time they viewed the page. They should be able to browse away from the page, come back, and pick up where they left off.

In Django, it's reasonable to store those filter settings in the user's session, which will persist as long as they are logged in. You could easily code this up inside a particular view. But if this is something you do a lot, it makes more sense to extract the logic into a view decorator. Here is a generic decorator you can apply to any view to have a subset of the query parameters "stick" between renders.

from django.http import HttpResponseRedirect
import urlparse
import urllib

def remember_last_query_params(url_name, query_params):

    """Stores the specified list of query params from the last time this user
    looked at this URL (by url_name). Stores the last values in the session.
    If the view is subsequently rendered w/o specifying ANY of the query params,
    it will redirect to the same URL with the last query params added to the URL.

    url_name is a unique identifier key for this view or view type if you want
    to group multiple views together in terms of shared history

    Example:

    @remember_last_query_params("jobs", ["category", "location"])
    def myview(request):
        pass

    """

    def is_query_params_specified(request, query_params):
        """ Are any of the query parameters we are interested in on this request URL?"""
        for current_param in request.GET:
            if current_param in query_params:
                return True
        return False

    def params_from_last_time(request, key_prefix, query_params):
        """ Gets a dictionary of JUST the params from the last render with values """
        params = {}
        for query_param in query_params:
            last_value = request.session.get(key_prefix + query_param)
            if last_value:
                params[query_param] = last_value
        return params

    def update_url(url, params):
        """ update an existing URL with or without paramters to include new parameters
        from http://stackoverflow.com/questions/2506379/add-params-to-given-url-in-python
        """
        if not params:
            return url
        if not url: # handle None
            url = ""
        url_parts = list(urlparse.urlparse(url))
        # http://docs.python.org/library/urlparse.html#urlparse.urlparse, part 4 == params
        query = dict(urlparse.parse_qsl(url_parts[4]))
        query.update(params)
        url_parts[4] = urllib.urlencode(query)
        return urlparse.urlunparse(url_parts)

    def do_decorator(view_func):

        def decorator(*args, **kwargs):

            request = args[0]

            key_prefix =  url_name + "_"

            if is_query_params_specified(request, query_params):
                for query_param in query_params:
                    request.session[key_prefix + query_param] = request.GET.get(query_param)

            else:
                last_params = params_from_last_time(request, key_prefix, query_params)
                if last_params and last_params != {}:
                    current_url = "%s?%s" % (request.META.get("PATH_INFO"), request.META.get("QUERY_STRING"))
                    new_url = update_url(current_url, last_params)
                    return HttpResponseRedirect(new_url)

            return view_func(*args, **kwargs)

        return decorator

    return do_decorator



Source: http://bitkickers.blogspot.com/2011/09/django-sticky-url-query-parameters-per.html

Database Django (web framework)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Blocking Ads on Your Network Using Raspberry Pi 3 + Fedora + Pi-hole
  • How To Evaluate Software Quality Assurance Success: KPIs, SLAs, Release Cycles, and Costs
  • Java Microservices: Code Examples, Tutorials, and More
  • SQL GROUP BY and Functional Dependencies: a Very Useful Feature

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo