1

I have a date filter that I am passing through several django views:

views.py

def event_list(request):
    date_query = request.GET.get("date", str(default_event_date()))
    d = datetime.strptime(date_query, "%Y-%m-%d").date()
    # do stuff...

    return render(request, "events/event_list.html", context)

But I would like to carry forward the GET parameters through the render().

I've found this answer for how to do this using reverse(), but render() doesn't take a url directly.

I suspect I need to add it back in to the request that is passed, but I'm not sure how to do this.

4
  • What do you mean "carry forward through render ()" ??? Commented Dec 27, 2016 at 6:44
  • I mean, after I render, I want the url to have ?date=2016-12-30 at the end Commented Dec 27, 2016 at 6:57
  • Could you also please paste the snippet of the relevant portion of your urls.py file? Commented Dec 27, 2016 at 7:08
  • url(r'^$', views.event_list, name='list'), Commented Dec 27, 2016 at 7:10

1 Answer 1

1

I think you are misunderstanding render. render’s job in life is to return an HttpResponse with content to the user from an HTML template and a context dictionary:

Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text.

In contrast, redirect redirects the user to a new URL (i.e., so GET parameters can be included). Thus, if you use render, you have to preserve your GET parmeters manually. Of course, you can avoid this by adding date to the user’s session by doing something like:

from datetime import date, datetime

date_query = request.session.get('date')
if not date_query:
    date_query = request.GET.get("date", default_event_date())
    if not isinstance(date_query, date):
        date_query = datetime.strptime(date_query, "%Y-%m-%d").date()
    request.session['date'] = date_query

d = date_query

And this will let you “carry forward” your GET parameters to subsequent routes and views.

Sign up to request clarification or add additional context in comments.

3 Comments

How do I preserve the GET parameters manually? Apologies for the poorly worded question, but that's what I meant.
The GET parameters shouldn’t change for this particular render. They should only change on page turn from the rendered page to the next page. So preserving your GET parameters means formatting your query string (using request.GET.urlencode) and appending it to each URL on which you would like the date parameter.
Thanks for the session suggestion. I think this might be a better solution anyway. I'm going to try it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.