[Django]-How Do I Handle Ampersands in Django URLs?

8👍

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

4👍

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)

Leave a comment