user3199840
user3199840

Reputation: 535

Django Urlpatterns, Include and slugs not working

I'm struggling with URLs and slugs. In my urlpatterns I want to do this:

url(r'^(?P<slug>.+)/', include([
    url(r'^$', 'myapp.views.MainCity'),
    url(r'^form/(?P<id>\d+)/$', 'myapp.views.Showform'), # Problem here   
])),

Lets say the slug is a city that will take you to the main page for that city. Every city has a list of events. And each events has a button with href="form/{{ event.id }}" that loads (jquery ajax) a form into a bootstrap modal-window. But it keeps trying to load the MainCity page into the modal instead of the '/form/id' url

def MainCity(request, slug):
    city = get_object_or_404(City, slug='slug')
    events = city.events.all().order_by('-date')
    context = {'city': city, 'events':events} 
    return render_to_response('index.html', context, context_instance=RequestContext(request)) 

def Showform(request, id):
    form = SomeForm()
    e = Events.objects.get(pk=id)
    # form handling etc..
    return render_to_respone('form.html', {'form': form, 'e':e}, context_instance=RequestContext(request))

This set-up seems to work if I hardcode the city-name into the urlpatterns. I finds and loads the form. But not when I use slug then it goes straight for the MainCity-view. So whats the correct way to structure this?

Upvotes: 0

Views: 201

Answers (1)

Alasdair
Alasdair

Reputation: 308889

The problem is that .+ matches any character, including forward slashes.

A more common regex for slugs would be [-\w]+.

Upvotes: 2

Related Questions