tags:

views:

209

answers:

6

How can I have URLs like example.com/category/catename-operation/ in Django?

Also in some cases the user enters a space separated category, how can I handle that? E.g if the user enters the category as "my home", then the URL for this category will become example.com/my home/ which is not a valid URL.

How can I handle these things?

+3  A: 

http://example.com/my%20home/ is a valid URL where space character is escaped and Django will do all escaping/unescaping for you.

Denis Otkidach
You can you the http://docs.python.org/library/urllib.html#urllib.quote to quote a URL correctly. Within a Django app, simply use http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse to create the proper URL for a specific view function with all of it's arguments filled in and correctly quoted.
S.Lott
A: 

You could consider adding a URL-friendly name to your category and using that in the URL instead.

As another example you could have example.com/tv/ and have the category called "Televisions."

badp
A: 

How can I handle these things?

If you want to handle this thing, to obtain my-url, then use the form field clean method to return the valid url. Thats what it is meant for.

Lakshman Prasad
+5  A: 

If you want to keep your URLs pretty, for example when a user enters "my category" you could have "my-category" instead of "my%20category" in the URL. I suggest you look into SlugField (http://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield) and prepopulating that slugfield using ModelAdmin's prepopulated_fields attribute.

StephenPaulger
here is a field that will slugify the content of another field for you, on save: http://gist.github.com/242001
Carson
A: 

You can use the slugify template tag within your views to deal with spaces and such like so:

from django.template.defaultfilters import slugify
slugify("This is a slug!") # Will return u'this-is-a-slug'
Josh Ourisman
A: 

You can try an improved version of SlugField called AutoSlugField which is part of Django Custom Management Command Extensions.

dannyroa