开发者

Django urls/slugs@#!

I have a genre category and a sub genre category and I'm trying to use dynamic routing, here is my code:

models:

from django.db import models
from django.db.models import permalink

class Genre(models.Model):
    name = models.CharField(max_length=300)
    slug = models.SlugField(max_length=150)

def __unicode__(self):
    return u'%s' % self.name

@models.permalink
def ge开发者_开发知识库t_absolute_url(self):
    return ('view_genre', (), { 'genre_slug' : self.slug })

class SubGenre(models.Model):
    genre = models.ForeignKey(Genre)
    name = models.CharField(max_length=300)
    slug = models.SlugField(max_length=150) 

def __unicode__(self):
    return u'%s' % self.name

@models.permalink
def get_absolute_url(self):
    return ('view_subgenre', (), { 'subgenre_slug' : self.slug })

my views:

from django.template import Context, loader, RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.core import serializers

def index(request):
    return render_to_response("home.html", context_instance=RequestContext(request),)

def genre(request, slug):
    genre = get_object_or_404(Genre, slug=genre_slug)
    return render_to_response("genre.html", {'subgenre':       SubGenre.objects.filter(genre=genre)}, context_instance=RequestContext(request),)

and my ulrs:

from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
# Example:
(r'^home/', 'home.views.index'),
url(r'^home/(?P<genre_slug>[-\w]+)/$', 'home.views.genre', name='view_genre'),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root':   settings.MEDIA_ROOT}),

# Uncomment the admin/doc line below to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),

# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
)

I got no idea why the routing isn't working. Perhaps somebody could point me in the right direction?


Despite your reluctance to give any examples of URLs which don't work, the problem is probably in the first URL. Because you haven't terminated that with $, to indicate that the slash is the end of the pattern, it will match all URLs beginning with home/.

Do this instead:

(r'^home/$', 'home.views.index'),
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜