Django is giving trouble on urls to catch and forward to a view. (slug fields)
I am currently making views
called by slug
s on django
but I seem to have some troubles on that.
Suppose I have database entries like de
ce
ceiling
(slug fields
).
Now when I call, myapp/ce
or myapp/de
. It returns the view I want. But when I call myapp/ceiling
, it returns 404
.
No sculpture found matching the query
It catches the url though.
The problem occurs when I use capital letter on the name
field. The other fields hold lowercase
.
I failed to understand this behavior.
My code is as follows:
urls.py
urlpatterns = patterns('sculptures.views',
(r'^$', SculptureListView.as_view()),
(r'^(?P<slug>[\w-]+)/$', SculptureDetailView.as_view()),
)
views.py
class SculptureDetailView(DetailView):
context_object_name = 'sculpture'
def get_queryset(self):
sc开发者_运维知识库ulpture_slug = get_object_or_404(Sculpture, slug__iexact=self.kwargs['slug'])
return Sculpture.objects.filter(slug=sculpture_slug)
Looking at your code:
def get_queryset(self):
sculpture_slug = get_object_or_404(Sculpture, slug__iexact=self.kwargs['slug'])
Here you're fetching the Sculpture
object that matches the captured slug.
return Sculpture.objects.filter(slug=sculpture_slug)
And then you get the Sculpture
object whose slug is another Sculpture
object. I wonder how this even works in some cases :)
Since you have a DetailView
, you can directly use get_object()
:
class SculptureDetailView(DetailView):
def get_object(self):
return get_object_or_404(Sculpture, slug__iexact=self.kwargs['slug'])
精彩评论