Skip to content

Instantly share code, notes, and snippets.

@j0rdm4n
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j0rdm4n/265d3bfa57d2149edb04 to your computer and use it in GitHub Desktop.
Save j0rdm4n/265d3bfa57d2149edb04 to your computer and use it in GitHub Desktop.
Generic detail view must be called with either an object pk or a slug
#Django error :Generic detail view must be called with either an object pk or a slug
#http://computernerddiaries.wordpress.com/
class PostView(DetailView):
template_name = 'post_detail.html'
context_object_name = 'post'
model = Post
class Post(models.Model):
title = models.CharField(max_length=50, unique=True)
slug = models.SlugField(unique=True)
content = models.TextField()
def __str__(self):
return self.title
#by pk
urlpatterns = patterns('',
# ...
url(r'^(?P<pk>\d+)/$', PostView.as_view(), name='post_detail_url'),
)
#by slug
urlpatterns = patterns('',
# ...
url(r'^(?P<slug>\w+)/$', PostView.as_view(), name='post_detail_url'),
)
#by title
#first override the get_object method of DetailView
class PostView(DetailView):
template_name = 'post_detail.html'
context_object_name = 'post'
model = Post
def get_object(self):
object = get_object_or_404(Post,title=self.kwargs['title'])
return object
#then
urlpatterns = patterns('',
# ...
url(r'^(?P<title>\w+)/$', PostView.as_view(), name='post_detail_url'),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment