Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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()
like image 250
slaughterize Avatar asked Apr 18 '14 12:04

slaughterize


People also ask

What is Pk_url_kwarg?

pk_url_kwarg. The name of the URLConf keyword argument that contains the primary key. By default, pk_url_kwarg is 'pk' . context_object_name. Designates the name of the variable to use in the context.


4 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.

like image 119
Alex Avatar answered Oct 17 '22 02:10

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.

like image 35
Robin Avatar answered Oct 17 '22 01:10

Robin


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.

like image 7
radtek Avatar answered Oct 17 '22 02:10

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()),
]
like image 6
koderstory Avatar answered Oct 17 '22 03:10

koderstory