Skip to content Skip to sidebar Skip to footer

How To Have A Url Like This In Django?

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 e

Solution 1:

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.

Solution 2:

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

Solution 3:

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'

Solution 4:

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

Solution 5:

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."

Post a Comment for "How To Have A Url Like This In Django?"