Django: Generic detail view must be called with either an object pk or a slug

Question:

Getting this error when submitting the form associated with this view. Not sure what exactly is the problem, considering I have a form with a very similar structure and it works fine.

#views.py
class Facture_Creer(SuccessMessageMixin, CreateView):
    model = Facture
    template_name = "facturation/nouvelle_facture.html"
    form_class= FormulaireFacture

    # permet de retourner a l'URL pointant vers le membre modifie
    def get_success_url(self):
        return reverse_lazy('facture_consulter',kwargs={'pk': self.get_object().id})

class Facture_Update(SuccessMessageMixin, UpdateView):
    model = Facture
    template_name = "facturation/nouvelle_facture.html"
    form_class= FormulaireFacture
    success_message = "Facture mise à jour avec succes"

    # permet de retourner a l'URL pointant vers le membre modifie
    def get_success_url(self):
        return reverse_lazy('facture_consulter',kwargs={'pk': self.get_object().id})

#urls.py
urlpatterns = patterns('',
    url(r'^$', TemplateView.as_view(template_name="facturation/index.html")),
    url(r'^facture/$', FactureView.as_view()),
    url(r'^facture/(?P<id>d+)', FactureView.as_view(), name='facture_consulter'),
    url(r'^facture/ajouter/$', Facture_Creer.as_view(), name='facture_creer'),
    url(r'^facture/modifier/(?P<pk>d+)/$', Facture_Update.as_view(), name='facture_update'),
    url(r'^membre/ajouter/$', Membre_Creer.as_view(), name='membre_creer'),
    url(r'^membre/modifier/(?P<pk>d+)/$', Membre_Update.as_view(), name='membre_update'),
    #url(r'membre/(?P<pk>d+)/supprimer/$', Membre_Supp.as_view(), name='membre_delete')
)

urlpatterns += staticfiles_urlpatterns()
Asked By: slaughterize

||

Answers:

You need to pass an object identifier (pk or slug) so your views know which object they’re operating on.

Just to take an example from your urls.py:

url(r'^facture/ajouter/$', Facture_Creer.as_view(), name='facture_creer'),
url(r'^facture/modifier/(?P<pk>d+)/$', Facture_Update.as_view(), name='facture_update'),

See how the second one has (?P<pk>d+)/? That is passing a pk to the UpdateView so it knows which object to use. Thus if you go to facture/modifier/5/, then the UpdateView will modify object with pk of 5.

If you don’t want to pass a pk or slug in your url, you’ll need to override the get_object() method and get your object another way. Url here.

Answered By: Alex

As Alex suggests: for default Django behaviour you have to use “pk” in your url pattern.

If you wish to change the object identifier for the primary key “pk” to a different name, you can define pk_url_kwarg. This is available since Django 1.4.

Answered By: Robin

Update: In django 2.0.2, change this to:

url(r'^facture/modifier/<int:pk>/$', Facture_Update.as_view(), name='facture_update'),
Answered By: Linh

Hey all I used the new path() function and here is my working example that I’m sure will help:

views.py:

from django.views.generic.detail import DetailView

class ContentAmpView(DetailView):

    model = Content
    template_name = 'content_amp.html'  # Defaults to content_detail.html

urls.py:

from django.urls import path

from .views import ContentAmpView

# My pk is a string so using a slug converter here intead of int
urlpatterns = [
    path('<slug:pk>/amp', ContentAmpView.as_view(), name='content-amp'),
]

templates/content_amp.html

<!doctype html>
<html amp lang="en">
<head>
    <meta charset="utf-8">
    <script async src="https://cdn.ampproject.org/v0.js"></script>
    <title>Hello, AMPs</title>
    <link rel="canonical" href="http://example.ampproject.org/article-metadata.html">
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
    <script type="application/ld+json">
      {
        "@context": "http://schema.org",
        "@type": "NewsArticle",
        "headline": "Open-source framework for publishing content",
        "datePublished": "2015-10-07T12:02:41Z",
        "image": [
          "logo.jpg"
        ]
      }

    </script>
    <style amp-boilerplate>
        body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}
    </style>
    <noscript>
        <style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}
        </style>
    </noscript>
</head>
<body>
<h1>Welcome to AMP - {{ object.pk }}</h1>
<p>{{ object.titles.main }}</p>
<p>Reporter: {{ object.reporter }}</p>
<p>Date: {{ object.created_at|date }}</p>
</body>
</html>

Also note that in my settings.py, under TEMPLATES, I have 'APP_DIRS': True. More on path here.

Answered By: radtek

Like Robin said, you can use pk_url_kwarg if you want custom pk name.

But as addition, issue Generic detail view must be called with either an object pk or a slug raises also in slug.

So if you want to create custom slug field (no need to use pk or slug name). You can override slug_field and slug_url_kwarg in your DetailView class.

Here is just another example if you want url as Slug Field.

models.py

class Post(models.Model):
    title = models.CharField(max_length=255)
    url = models.SlugField()
    body = models.TextField()
    image = models.ImageField(upload_to='blog/', blank=True, null=True)

views.py

class ListPost(ListView):
    model = Post
    template_name = 'blog/list.html'
    paginate_by = 2
    context_object_name = 'posts'

class DetailPost(DetailView):
    model = Post
    template_name = 'blog/detail.html'
    slug_field = 'url'
    slug_url_kwarg = 'url'

urls.py

urlpatterns = [
    path('', ListPost.as_view()),
    path('<slug:url>/', DetailPost.as_view()),
]
Answered By: koderstory

I am using Django version 2.2.12,

Here is just another example this works fine for me :

models.py

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=256)
    author = models.CharField(max_length=256)
    pages = models.IntegerField()
    price = models.FloatField()

views.py

from django.views.generic import ListView,DetailView
from testapp.models import Book

class BookListView(ListView):
    model=Book

class BookDetailView(DetailView):
    model=Book

urls.py

from django.contrib import admin
from django.urls import path
from testapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.BookListView.as_view()),
    path('<slug:pk>/', views.BookDetailView.as_view()),
]
Answered By: Keerthi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.