views:

76

answers:

4

Hey all!

So, basically what I'm trying to do is a hockey pool application, and there are a ton of ways I should be able to filter to view the data. For example, filter by free agent, goals, assists, position, etc.

I'm planning on doing this with a bunch of query strings, but I'm not sure what the best approach would be to pass along the these query strings. Lets say I wanted to be on page 2 (as I'm using pagination for splitting the pages), sort by goals, and only show forwards, I would have the following query set:

?page=2&sort=g&position=f

But if I was on that page, and it was showing me all this corresponding info, if I was to click say, points instead of goals, I would still want all my other filters in tact, so like this:

?page=2&sort=p&position=f

Since HTTP is stateless, I'm having trouble on what the best approach to this would be.. If anyone has some good ideas they would be much appreciated, thanks ;)

Shawn J

A: 

Check out filter mechanism in the admin application, it includes dealing with dynamically constructed URLs with filter information supplied in the query string.

In addition - consider saving actual state information in cookies/sessions.

gorsky
+1  A: 

Have you looked at django-filter? It's really awesome.

Baresi
+2  A: 

Firstly, think about whether you really want to save all the parameters each time. In the example you give, you change the sort order but preserve the page number. Does this really make sense, considering you will now have different elements on that page. Even more, if you change the filters, the currently selected page number might not even exist.

Anyway, assuming that is what you want, you don't need to worry about state or cookies or any of that, seeing as all the information you need is already in the GET parameters. All you need to do is to replace one of these parameters as required, then re-encode the string. Easy to do in a template tag, since GET parameters are stored as a QueryDict which is basically just a dictionary.

Something like (untested):

@register.simple_tag
def url_with_changed_parameter(request, param, value):
    params = request.GET
    request[param] = value
    return "%s?%s" % (request.path, params.urlencode())

and you would use it in your template:

{% url_with_changed_parameter request "page" 2 %}
Daniel Roseman
Hmm, now that you mention it, you're right after filtering new information, such as position, I probably would want to start from the first page. Your solution works for a lot of cases though, I'll implement it tomorrow after some sleep. :)
shawnjan
A: 

If You want to save all the "parameters", I'd say they are resource identifiers and should normally be the part of URI.

Almad