A sample url in the browser might look like this:
http://127.0.0.1:8000/data/pos/20060922/dle/?filter=inst__exposure_asset_class:9&page=2
Which maps to this URL conf:
# positions
(r'^pos/(?P<date>\d{8})/(?P<fund>.*)/$',
'pfweb.core.views.list_positions'),
And uses this view:
def list_positions(request, date, fund):
positions = Position.objects.filter(
date=date,
account__custodian__portfolio__fund_name=fund)
if request.has_key('filter'):
# account__name:abc,spectrum:123
kwargs = dict([kv.split(':') for kv in
request['filter'].split(',')])
positions = positions.filter(**kwargs)
# HACK post message to django groups to see if there is a better
way...
# get a url suitable for paging by starting with the original
# and stripping off any 'page=' part
nav_base_url = request.META['PATH_INFO'] + '?'
query_string = re.sub(r'[?&]page=\d+', r'',
request.META['QUERY_STRING'])
if query_string:
nav_base_url += query_string + '&'
return object_list(
request,
positions,
paginate_by=30,
extra_context={'nav_base_url':nav_base_url})
Notice that I'm passing back the 'nav_base_url' to the template so I
can setup the previous/next links for paging. I also plan to use that
url for sorting links in column headers.
But its a little nasty. Starting at the HACK comment you can see that
I'm digging into the request meta info to get the url path and query
string, strip off any 'page=nnn' fragment and return a base url that I
can append the 'page=nnn' or 'sort=xxx' in my template, like this:
{% if has_previous %}
<a href="{{ nav_base_url }}page={{ previous }}">Prev</a>
{% endif %}
{% if has_next %}
<a href="{{ nav_base_url }}page={{ next }}">Next</a>
{% endif %}
It seems this is part of (what I would think would be) a general
problem: building a link in a page back to the same view using the same
args, but optionally adding or replacing certain fields within that
url.
Does anyone see a cleaner, more elegant way to solve this without
manually parsing and building a query string? I'm worried that as this
gets more complex, there will be all sorts of bugs with issues like
getting the '?' and '&' in the right place.
Thanks in advance,
-Dave