U
U
Untiwe2021-01-23 21:55:05
Django
Untiwe, 2021-01-23 21:55:05

How to pass url slug parameter to DetailView?

I'm trying to make a user page that would access the page by username

urls.py in the main folder

urlpatterns = [
   #others
    path('user/', include('user.urls')),    
]

urls.py in application folder
from django.urls import path
from user.views import *
urlpatterns = [
    path('<slug:username>/', UserView.as_view(), name='userview'),
]

views.py code
from mymodels.models import CustomUser
from django.views.generic.detail import DetailView

class UserView(DetailView):
    model = CustomUser
    template_name = 'user/user.html'


The result is an error:
Generic detail view UserView must be called with either an object pk or a slug in the URLconf.

But if you use pk
urlpatterns = [
    path('<int:pk>/', UserView.as_view(), name='userview'),
]

Then everything works

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dr. Bacon, 2021-01-23
@bacon

I highly recommend studying the sources of these views, the parameters specified in the path are in self.kwargs
PS Since I changed the question, in addition, you need to override the get_object method

U
Untiwe, 2021-01-23
@Untiwe

It was necessary to override the get_object method. It can be omitted only if pk is used because it is used by default.
Minimum solution:

class UserView(DetailView):
    model = CustomUser
    template_name = 'user/user.html'

    def get_object(self):
        pass

But I don't fully understand how it works. I would be glad for an explanation or a link to the documentation , this did not give a complete picture

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question