views:

57

answers:

1

Is there a way to add get variables into the url while using permalink?

So www.example.com/1999/news/?filter=entertainment

A: 

IMHO Permalink should not contain a query parameter. It doesn't quite sound right.

That said, there is a very crufty and un-Django like way to return an URL like the one you have specified from the get_absolute_url() method of a model.

Steps

First add a dummy URL and corresponding do-nothing view. For e.g.

# models.py
class MyModel(models.Model):
    ...
    @models.permalink
    def get_absolute_url(self):
        return ('dummy_url', [str(self.id), self.filter])

# urls.py
url(r'^news/(?P<model_id>\d+)/\?category=(?P<category>\w+)$', 
    'dummy_url', {}, name = 'dummy_url'),

# views.py
def dummy_url(request, *args, **kwargs):
    pass

This dummy will only serve to generate the URL. I.e. you will get the correct URL if you execute instance.get_absolute_url().

You will have to add another, proper URL configuration and a matching view to actually display the instance page when the URL is called. Something like this.

# urls.py
url(r'^news/(?P<model_id>\d+)/$', 
    'correct_view', {}, name = 'correct_view'),

# views.py
def correct_view(request, *args, **kwargs):
    # do the required stuff.

The correct_view will have to extract the GET parameter from the request though.

Note how similar the dummy and proper URL configurations are. Only the query parameter is extra in the dummy.

Manoj Govindan
hm, wow. ok, so if i don't use a get param, then how would i be able to pass in text that may include things like space or ', etc?
See this question. It is about passing text with spaces to an URL. http://stackoverflow.com/q/3675368/140185 Also, can you not pass an id or a slug instead of the field with spaces/commas?
Manoj Govindan
i'm trying to pass the name of a person. Since it can appear as a link in places, a POST doesn't seem right. A slug may work, but is it right to have an apostrophe in the url? That doesn't look right
IIRC slugs don't have apostrophes. At least the ones generated by `from django.template.defaultfilters.slugify` don't. So you should be safe with slugs I think.
Manoj Govindan
But I guess my question is, what if I need the apostrophe? The slugs, I believe, just strips them because it's not accurate (caps, apostrophes, etc), but supposed to be a representation.
I'm afraid I don't know how best to go about it in that case. I suspect that adding an URL config with both `\w` and `\W` _may_ solve your purpose.
Manoj Govindan