Django URL Variables - Business Name in URL in stead of ID

Trying to pass Business Name in URL in stead of ID. When I pass IDs, everything is fine.

url(r'^(?P<name>\w+)/$', ''),

def business(request, name=1):
    return render_to_response('business.html', 
                             {'business': business.objects.get(name=name) })


<a href="{{|slugify }}/">Name{{ }}</a>

When I do this, it will only work for single word business name such as "Bank" however if the business has multiple words "Wells Fargo" it will not work.

My goal is to use slugify to pass short SEO friendly URL such as

Thanks for your time and for your help!


First of all, you need to allow dashes in your url configuration:

url(r'^(?P<name>[-\w]+)/$', ''),

[-\w]+ matches "alphanumeric" characters in any case, underscore (_) and a dash.

Also, in the view, you need to "unslugify" the value passed in:

def business(request, name='unknown'):
    name = name.replace('-', ' ').capitalize()
    return render_to_response('business.html', 
                             {'business': business.objects.get(name=name) })

Also see:

Hope that helps.

Accordint to re module docs \w:

matches any alphanumeric character and the underscore

and the url you are trying to match has a dash because django's slugify method converts spaces and some non-ascii chars into dashes. So the fix consists in modifying the pattern to:

url(r'^(?P<name>[\w-]+)/$', ''),

But this isn't enough. Your current view will try to get a Business instance with the slugified name and will throw a DoesNotExists exception. So you should do one of the folowing things:

  • Add an slug field to your Business model which value must be slugify(

  • or add an id to the url, like this:

    url(r'^(?P[\w-]+)/(?P\d+)/$', ''),

and modify your view to get the instance by id:

def business(request, name, obj_id):
    return render_to_response('business.html', {'business': business.objects.get(id=obj_id) })

Need Your Help

refresh fragment when dialogFragment dismiss

android fragment android-dialogfragment

in my application, my Fragment AppointmentFrag contains a customListView which load data from database

Unnecessary padding in CardView?

android android-layout android-5.0-lollipop android-cardview

I have implemented CardView in my app and everything works fine except there is a little padding around the image if I put radius to the card.