[Fixed]-How can I keep GET instance on template form after submission?

0👍

There is a simple way to do so :

<input type="text" name="title" value="{{ request.POST.title }}">

After the form submit it will keep the POST title field value and use it as the input value.

1👍

You can use this sticky query method decorator on your view.

from urllib.parse import urlencode
try:
    import urlparse
except ImportError:
    from urllib import parse as urlparse

import wrapt

from django.http import HttpResponseRedirect


'''
Originally From:
https://www.snip2code.com/Snippet/430476/-refactor--Django--sticky-URL-query-para
'''

"""
File: decorators.py
Author: timfeirg
Email: kkcocogogo@gmail.com
Github: https://github.com/timfeirg/
Description: remember_last_query_params is from
http://chase-seibert.github.io/blog/2011/09/02/django-sticky-url-query-parameters-per-view.html
"""


class sticky_query(object):

    """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 __init__(self, views_name, query_params):
        self._cookie_prefix = views_name + '_'
        self._query_params = list(set(
            query_params + ['page', 'paginate_by', 'order_by_fields']))

    def _get_sticky_params(self, request):
        """
        Are any of the query parameters we are interested in on this request
        URL?
        """
        gum = []
        for current_param, v in request.GET.items():
            if current_param in self._query_params:
                gum.append(current_param)
        return gum

    def _get_last_used_params(self, session):
        """
        Gets a dictionary of JUST the params from the last render with values
        """
        litter = {}
        for k in self._query_params:
            last_value = session.get(self._cookie_prefix + k, None)
            if last_value:
                litter[k] = last_value

        return litter

    def _digest(self, current_url, litter):
        """
        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
        """
        parse_res = urlparse.urlparse(current_url)
        # part 4 == params
        query = dict(urlparse.parse_qsl(parse_res[4]))
        query.update(litter)
        query = urlencode(query)
        parse_res = urlparse.ParseResult(
            parse_res[0], parse_res[1], parse_res[2], parse_res[3], query,
            parse_res[5])
        new_url = urlparse.urlunparse(parse_res)
        return new_url

    @wrapt.decorator
    def __call__(self, wrapped, instance, args, kwargs):
        request = args[0]
        session = request.session
        query = request.GET
        gum = self._get_sticky_params(request)
        if gum:
            for k in gum:
                sticky_key = self._cookie_prefix + k
                session[sticky_key] = query[k]
        else:
            meta = request.META
            litter = self._get_last_used_params(session)
            if litter:
                current_url = '{0}?{1}'.format(
                    meta['PATH_INFO'], meta['QUERY_STRING'])
                new_url = self._digest(current_url, litter)
                return HttpResponseRedirect(new_url)

        return wrapped(*args, **kwargs)

Use this decorator on your view:

from django.utils.decorators import method_decorator

@method_decorator(sticky_query("search_page", ["title"]), name='dispatch')

Leave a comment