slugfield example python django

python - example - Django: la vista de detalle genérica debe llamarse con un objeto pk o con un slug



django slugfield example (4)

Recibiendo este error al enviar el formulario asociado con esta vista. No estoy seguro de cuál es exactamente el problema, considerando que tengo un formulario con una estructura muy similar y funciona bien.

#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()


Actualización: En django 2.0.2, cambia esto a:

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


Como sugiere Alex: para el comportamiento predeterminado de Django, debes usar "pk" en tu patrón de URL.

Si desea cambiar el identificador de objeto para la clave principal "pk" a un nombre diferente, puede definir pk_url_kwarg . Esto está disponible desde Django 1.4.


Debe pasar un identificador de objeto (pk o slug) para que sus vistas sepan en qué objeto están operando.

Solo para tomar un ejemplo de su 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''),

Vea cómo el segundo tiene (?P<pk>/d+)/ ? Eso es pasar un pk a UpdateView para que sepa qué objeto usar. Por lo tanto, si va a facture/modifier/5/ , UpdateView modificará el objeto con un pk de 5.

Si no quieres pasar un pk o slug en tu url, deberás anular el método get_object y obtener tu objeto de otra manera. Url here .


Hola, todos usé la nueva función path() y aquí está mi ejemplo de trabajo que estoy seguro que ayudará:

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>

También tenga en cuenta que en mi settings.py , bajo TEMPLATES , tengo ''APP_DIRS'': True . Más en camino here .