简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM