Passing Pk or Slug to Generic DetailView in Django? - python

I am new to Django Class based views. I am trying to make a simple view to get details of a post.
My views.py:
from django.views.generic import ListView, View, DetailView
class GenreDetail(DetailView):
model = Post
template_name = "post.html"
My urls.py:
urlpatterns = [
url(r'(?P<post_id>[^/]+)', GenreDetail.as_view(), name = 'post'),
url(r'(?P<post_id>[^/]+)/(?P<slug>[-\w]+)$', GenreDetail.as_view()),
]
Error that I get:
AttributeError at /2/memoirs-of-a-geisha-by-arthur-golden
Generic detail view GenreDetail must be called with either an object pk or a slug.
So the pk or slug is not passed to the Generic Detailview. How do I pass that ? I assume from url it can pick up but it's not.

url patterns are checked in the order you define them
so here:
urlpatterns = [
url(r'(?P<post_id>[^/]+)', GenreDetail.as_view(), name = 'post'),
url(r'(?P<post_id>[^/]+)/(?P<slug>[-\w]+)$', GenreDetail.as_view()),
]
...the first pattern is getting matched (because it does not end with $ so the extra segment is just ignored)
...and that pattern only passes a single keyword arg
Generally it is a bad idea to have multiple url patterns pointing to the same view. If possible you should try and make a single regex (eg using optional groups) which handles the various cases of the url for a particular view. It's more explicit that way.
On the other hand, simply reversing the order of your patterns to put the more explicit one first would also work and be correct (this is the Django rule of urlpatterns!)
urlpatterns = [
url(r'(?P<post_id>[^/]+)/(?P<slug>[-\w]+)$', GenreDetail.as_view()),
url(r'(?P<post_id>[^/]+)', GenreDetail.as_view(), name = 'post'),
]
As #ozgur mentions you also need to tell the view to use post_id instead of pk by setting pk_url_kwarg

If you want to fetch details using either post_id or slug then your urls should be like this
url(r'post/(?P<post_id>\d+)/$', GenreDetail.as_view(), name = 'post_detail'),
url(r'post/(?P<slug>[-\w]+)/$', GenreDetail.as_view(), name = 'post_detail_slug'),
And your view should be like this
from django.views.generic import DetailView
class GenreDetail(DetailView):
model = Post
template_name = "post.html"
pk_url_kwarg = "post_id"
slug_url_kwarg = 'slug'
query_pk_and_slug = True
For more details please read the docs.

The problem is that you have to tell DetailView that it should use post_id keyword in the URL instead of default ones pk or slug in order to get the object that will be displayed.
This can be done by setting pk_url_kwarg attribute:
(Your url definition is also wrong, always end your url definitions with $. Below is the corrected version)
url(r'(?P<post_id>\d+)$', GenreDetail.as_view(), name = 'post'),
url(r'(?P<post_id>\d+)/(?P<slug>[-\w]+)$', GenreDetail.as_view()),
The following urls will match given the url patterns above:
/2
/2/memoirs-of-a-geisha-by-arthur-golden
from django.views.generic import DetailView
class GenreDetail(DetailView):
model = Post
template_name = "post.html"
pk_url_kwarg = "post_id"
Alternatively, you can just change post_id to pk in your url so you don't have to touch anything in your view:
url(r'(?P<pk>\d+)$', GenreDetail.as_view(), name = 'post'),
url(r'(?P<pk>\d+)/(?P<slug>[-\w]+)$', GenreDetail.as_view()),

Using path:
from django.urls import path
from . import views
urlpatterns = [
path('<pk>/', views.GenreDetail.as_view(), name="post")]
For slug:
path('<slug:slug>/', views.GenreDetail.as_view(), name="post")

Related

Use URL data to fill form in Django with Class Based Views

I have 2 Models: Projects and Members, each one with a form. I was able to add to the URL the number of the project (id) this:
class PageCreate(CreateView):
model = Page
form_class = PageForm
success_url = reverse_lazy('members:create')
def get_success_url(self):
return reverse_lazy('members:create', args=[self.object.id])
When I finish of filling the Project form, it redirects the page to the Member form.
What I want to do is to extract the ID of the Project from the URL and use it in the Member form. I cannot think any other solution.
Currently I have a Selection list to select the Project in the Member form but I want the Project loaded as soon as is created.
I am using the CreateView in the models for both Projects and Members. This is the view for MemberCreate
#method_decorator(login_required, name='dispatch')
class MemberCreate(CreateView):
model = Member
form_class = MemberForm
success_url = reverse_lazy('pages:pages')
Only attempt I had to visualize the ID in the HTML was using
{{ request.get }}
To somehow get the value from the GET but I could not do it.
Url Parameters
import imp
from django.urls import path
from .views import PageListView, PageDetailView, PageCreate, PageUpdate, PageDelete, MemberCreate, MemberDelete, MemberUpdate
pages_patterns = ([
path('', PageListView.as_view(), name='pages'),
path('<int:pk>/<slug:slug>/', PageDetailView.as_view(), name='page'),
path('create/', PageCreate.as_view(), name='create'),
path('update/<int:pk>', PageUpdate.as_view(), name='update'),
path('delete/<int:pk>', PageDelete.as_view(), name='delete'),
], 'pages')
members_patterns = ([
path('create/<int:pk>', MemberCreate.as_view(), name='create'),
path('update/<int:pk>', MemberUpdate.as_view(), name='update'),
path('delete/<int:pk>', MemberDelete.as_view(), name='delete'),
], 'members')
Stuff parsed from the URL ends up in the view's self.kwargs. From
return reverse_lazy('members:create', args=[self.object.id])
you pass through an URL like
path( 'create/<int:project>', MemberCreateView.as_view(), name='create' )
and in the view, the id is now self.kwargs['project']. (note, an URL can specify multiple named variables separated by slashes, it's not limited to just one). You typically then use
project = Project.objects.get( pk = self.kwargs['project'] )
Request.GET is something different: it's where the dict encoded as a querystring goes. If your client supplies
http://server/app/foo?bar=27&baz=hello
then when you arrive in the view which handles app/foo, request.GET contains
{ 'bar':'27', 'baz':'hello' }
(actually it's a QueryDict, not a Python dict, which has some subtle diffreernces. Consult the Django documentation. The main difference is that the values attached to keys can be multi-valued, for a querystring like ?bar=27&bar=54&bar=silly

Implement REST API with Django

This is my Django model:
class M(models.Model):
a = models.IntegerField()
b = models.IntegerField()
This is the serializer:
class MSerializer(ModelSerializer):
class Meta:
model = M
fields = ['a', 'b']
I would like to be able to implement these REST APIs:
127.0.0.1:8000/m/ (GET list of all elements, POST new element)
127.0.0.1:8000/m/:id/ (GET details of element with id id)
127.0.0.1:8000/n/:a/m/ (GET all elements with a specific a field)
So far this is the view and urls that I implemented:
class MViewSet(ModelViewSet):
queryset = M.objects.all()
serializer_class = MSerializer
router = DefaultRouter()
router.register(r'm', MViewSet)
urlpatterns = [
path('', include(router.urls)),
]
However, in this way the third use case is not working. How can I modify my code to make the third case work? I'd prefer to use as few lines of code as possible (i.e., I would like to use some Django built-in functionalities).
Since it look like you want the 3rd endpoint on another root (possibly another app name n), I'll implement it is a standalone API view, and not as an action on a viewset (although both options are possible)
class FilteredMListView(ListAPIView):
serializer_class = MSerializer
def get_queryset(self):
return M.objects.filter(a=self.kwargs["a"])
Then you register it to the router using:
urlpatterns = [
path("n/<str:a>/m/", FilteredMListView.as_view())
]
For your 3rd case, I would use a ListAPIView, overriding the get_queryset method to filter by the passed value for a. The idea is that when get_queryset method is invoked, and with as many other filters you'd like to implement, the condition for a is always present. Since the value for a will be in the url, it is mandatory, and you always have in in the view's kwargs. Would look like this:
urls.py
router = DefaultRouter()
router.register(r'm', MViewSet)
urlpatterns = [
path('', include(router.urls)),
path('<a>/m', AValuesListApiView.as_view()
]
views.py
class AValuesListApiView(generics.ListAPIView):
queryset = M.objects.all()
serializer_class = MSerializer
def get_queryset(self):
return super().get_queryset().filter(score=self.kwargs["score"])

Django - URL not found using generic views

I am writing a basic Events app which contains of two modules(apps) so far : users and events.
I am using Django 2.1 with Python 3.6 on Ubuntu 16.04
So far, I've been able to handle users, but on events, I can't use Update, Detail and Delete generic views. All of them return 404.
My views.py:
class EventListView(ListView):
model = EventModel
template_name = 'event_list.html'
queryset = EventModel.objects.order_by('start_date_time')
class EventUpdateView(UpdateView):
model = EventModel
fields = ['event_type','start_date_time'
]
template_name = 'event_update.html'
class EventDeleteView(DeleteView):
model = EventModel
template_name = 'event_delete.html'
success_url = reverse_lazy('event_list')
class EventDetailView(DetailView):
model = EventModel
template_name = 'event_detail.html'
My urls.py (in project folder):
urlpatterns = [
path('', include('pages.urls')),
path('admin/', admin.site.urls),
path('users/', include('users.urls')),
path('users/', include('django.contrib.auth.urls')),
path('events/', include('events.urls')),
]
My urls.py (in events app):
urlpatterns = [
path('', views.EventListView.as_view(), name='event_list'),
path('<int:id>', views.EventDetailView.as_view(), name='event_detail'),
path('<int:id>/edit/', views.EventUpdateView.as_view(), name='event_update'),
path('<int:id>/delete/', views.EventDeleteView.as_view(), name='event_delete'),
]
What am I doing wrong? I've been searching the whole day and still have no idea how this might be wrong.
Note that the first line works (EventListView) but the other lines don't. By the way, I am using the book Django for Beginners. Most of the code here is identical to the code in the book.
Update
I don't use namespace in this application, the rest of urls.py is only some basic imports :
from django.urls import path
from . import views
The urls.py for the Project is like above, except it has include and admin as well.
The examples of URLs giving 404 error:
http://127.0.0.1:8000/events/1/
http://127.0.0.1:8000/events/1/edit/
PS I thought edit and delete give me 404, but actually the error is :
ImproperlyConfigured at /events/1/edit/
EventUpdateView is missing a QuerySet. Define EventUpdateView.model, EventUpdateView.queryset, or override EventUpdateView.get_queryset().)
In short: you defined a models (with s) attribute, but it should be model (without s).
Well the error actually already explains the problem:
ImproperlyConfigured at /events/1/edit/ EventUpdateView is missing a QuerySet.
Define EventUpdateView.model, EventUpdateView.queryset,
or override EventUpdateView.get_queryset().)
In your EventUpdateView you did not specify a model attribute, you wrote models, and for Django that is an entirely different attribute. So you should rename it to:
class EventListView(ListView):
model = EventModel
template_name = 'event_list.html'
queryset = EventModel.objects.order_by('start_date_time')
class EventUpdateView(UpdateView):
model = EventModel
fields = ['event_type','start_date_time'
]
template_name = 'event_update.html'
class EventDeleteView(DeleteView):
model = EventModel
template_name = 'event_delete.html'
success_url = reverse_lazy('event_list')
class EventDetailView(DetailView):
model = EventModel
template_name = 'event_detail.html'
For the EventListView, that did not matter, since you also defined a queryset attribute, and so Django took that one, but I would update it anyway.
Furthermore in the urls.py, you need to specify a pk parameter by default:
urlpatterns = [
path('', views.EventListView.as_view(), name='event_list'),
path('<int:pk>', views.EventDetailView.as_view(), name='event_detail'),
path('<int:pk>/edit/', views.EventUpdateView.as_view(), name='event_update'),
path('<int:pk>/delete/', views.EventDeleteView.as_view(), name='event_delete'),
]
Finally in the template you wrote something like:
{% url 'event_update' event.id %}
But apparently there was no event identifier, as a result the event.id is the string_if_invalid (by default the empty string), which is not an integer (well at least not if you did not specify that), and hence it can not find a relevant URL. After some discussion, it turned out that the correct identifier was object, so the correct url is something like:
{% url 'event_update' pk=object.id %}
The same of course should happen with other {% url ... %} calls.

Reverse not found in Django

This might be a simple one but I have been on this for hours, I must be missing something. Here we go:
urls.py:
urlpatterns = [
# Event patterns
url('^$', views.BuddyProgram.as_view(), name='buddy_program'),
url('^dashboard/$', views.BuddyDashboard.as_view(), name='buddy_dashboard'),
url('^thank-you/$', views.BuddyFinal.as_view(), name='final'),
url('^completed_intro/$', views.CompletedIntro.as_view(), name='buddy_completed_intro'),
url('^completed_passive_track/$', views.CompletedPassiveTrack.as_view(), name='buddy_completed_passive_track'),
url('^about/$', views.BuddyAbout.as_view(), name='buddy_about'),
url('^list/$', views.Buddies.as_view(model=BuddyProfile), name='buddies'),
url('^signup/$', views.BuddySignupView.as_view(), name='buddy_signup'),
# url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
url(r'^(?P<buddy_id>[0-9]+)/$', views.Buddy.as_view(model=BuddyProfile), name='buddy'),
]
views.py:
class BuddyFinal(TemplateView):
template_name = 'buddy/thank_you.html'
class BuddySignupView(SignupView):
template_name = 'buddy/buddy_create.html'
success_url = reverse('final') # profile specific success url
form_class = BuddySignupForm
profile_class = BuddyProfile # profile class goes here
def form_valid(self, form):
response = super(BuddySignupView, self).form_valid(form)
profile = self.profile_class(user=self.user)
profile.save()
return response
and the error I get:
django.core.urlresolvers.NoReverseMatch: Reverse for 'final' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
As your URLs aren't loaded yet when importing the BuddySignupView (and thus executing reverse), Django cannot find the URL.
You should use reverse_lazy instead: https://docs.djangoproject.com/en/1.11/ref/urlresolvers/#reverse-lazy
In your views.py file:
from django.core.urlresolvers import reverse_lazy
class BuddySignupView(SignupView):
template_name = 'buddy/buddy_create.html'
success_url = reverse_lazy('final') # profile specific success url
reverse_lazy only reverse the URL name at "runtime" (when Django actually needs the value) instead of "import time" when everything may not be available yet.
This error is coming because in any template file you are accecsing url(thank-you or signup) in wrong format. make sure about this url in html.

How do I use DateDetailView with a slug to render a page with a single article?

I am new to Django, and I am trying to have a separate page where I can view individual articles. Currently I have:
#views.py
class ArticleView(DateDetailView):
template_name = 'blog/article.html'
model = Article
date_field = "pub_date"
#I am not sure which one to use
slug_field = "unique_url_suffix"
slug_url_kwarg = 'unique_url_suffix'
and
#urls.py
urlpatterns = [
url(r'^(index\.html)?$',views.IndexView.as_view(),name='index'),
url(r'^(?P<year>[0-9]{4})/(?P<month>[-\w]+)/(?P<day>[0-9]+)/(?P<slug>[-\w]+)/$',
views.ArticleView.as_view(),
name="article_detail"),
]
and in index.html inside a loop of objects from the Article class:
<h2>{{article.title}}</h2>
I have also tried manually inputting the arguments, like this:
<h2>{{article.title}}</h2>
I keep on getting a "NoReverseMatch at /blog/" error. What am I doing incorrectly?
Edit: On top of the changes recommended for the answer, there was a typo causing problems. It does not affect the answer below, though.
First off, you should not be generating this URL in your template. You should define a get_absolute_url method in your Article model that looks like this:
from django.core.urlresolvers import reverse
def get_absolute_url(self):
# Note - you have to supply each of the date components separately
# because you need to match the URL regex.
return reverse (
'blog:article_detail',
kwargs={'year': self.pub_date.strftime("%Y"), 'month': self.pub_date.strftime("%b"),
'day': self.pub_date.strftime("%d"), 'slug': self.unique_url_suffix}
)
And then in your template:
<h2>{{article.title}}</h2>

Categories