简体   繁体   中英

Django: preserving GET parameters in URL template tag

I'm using a GET parameter in my Django app to pass in information, that I want to be preserved in future links using Django's {% url %} template tag.

In my case, this is to allow view-only access within the app.

Example URL:

https://my.app/entry/123?key=abcdef

An example link on that page is already created like this:

<a href="{% url 'entry_detail' entry.id %}">View more details</a>

Desired result:

I would like Django's URL template tag to automatically preserve any GET parameters named key throughout the app. In this case, it would generate new URLs with that same parameter applied. For example:

https://my.app/entry/123/details?key=abcdef

Workarounds

This blog post and this gist solve the problem by creating a new template tag and using that instead of Django's url template tag.

Is that really the best solution? I'd end up having to replace every instance of {% url %} throughout my app with my own tag. It also wouldn't fix the use ofreverse() .

Django middlewares may work for what you want. You could check when you receive the key parameter and store in session , then if there is not key parameter in the url append it:

class DetectKeyParameter:
    def __init__(self, get_response):
        self.get_response = get_response
         

@staticmethod
def process_view(request, view_func, view_args, view_kwargs): 
    return view_func(request, *view_args, **view_kwargs)


def __call__(self, request):
    if 'key' in request.GET:
        #If alerady is on the url just store it on session
        request.session['key'] = request.GET.get('key')
    else:
        if 'key' in request.session:         
            if not request.GET._mutable:
                #You need to change this property to add parameters to GET
                request.GET._mutable = True

                # now you can edit it
                request.GET['key'] = request.session['key']         
                request.GET._mutable = False
       
    response = self.get_response(request)        
    return response

This way, you'll have the key parameter on every request, until you delete the session variable. Perhaps the code doesn't work 100%, but I hope you get the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM