Jason Champion
Jason Champion

Reputation: 2750

How Do I Handle Ampersands in Django URLs?

I have a Django site that uses item names to create viewer-friendly URLs. For instance:

/item/DeluxeWidget/

I have an item that has an ampersand in the name:

/item/Red & Blue Widget/

The ampersand throws things off. If I use {{ widget.name|fix_ampersands }}, the ampersand will be escaped as & but it still isn't picked up in the URL pattern:

url(r"^widget/(?P<name>[0-9a-zA-Z&,. -]+)/$", 'site.views.widget' ),

In the view I use the captured name to do

Widget.objects.get(name=name)

What's the right combination of escaping, patterns, or filters to handle an ampersand in a URL? I also expect to run into names with apostrophes in them. Is there anything I should do to handle those too?

Upvotes: 3

Views: 1951

Answers (2)

Michael Mior
Michael Mior

Reputation: 28752

Consider using a SlugField which can automatically be filled with a cleaned up version of another field suitable for use in URLs.

Upvotes: 8

Jon Clements
Jon Clements

Reputation: 142206

Generally, you're best off not doing that, and following an SO kind of pattern - let's use this page for an example (http://stackoverflow.com/questions/13212960/how-do-i-handle-ampersands-in-django-urls)

Then you can do:

url(r"^widget/(?P<widget_id>[0-9]+)/(?P<widget_name>(.*?)/$", 'site.views.widget' ),

Then:

  • {{ widget.name|fix_ampersands }} becomes {{ widget.name|slugify }}
  • Widget.objects.get(name=name) becomes Widget.objects.get(pk=widget_id)

Upvotes: 4

Related Questions