How Do I Handle Ampersands in Django URLs?
django, django-urls, python, url
Solution
Consider using a SlugField which can automatically be filled with a cleaned up version of another field suitable for use in URLs.
Problem
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?