Last active
August 29, 2015 14:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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