Generic detail view ProfileView must be called with either an object pk or a slug
Asked Answered
B

2

6

I'm new to Django 2.0 and i'm getting this error when visiting my profile page view. It's working with urls like path('users/<int:id>') but i wanted to urls be like path('<username>'). Not sure what exactly is the problem. I hope you can help.

#views.py
class ProfileView(views.LoginRequiredMixin, generic.DetailView):
    model = models.User
    template_name = 'accounts/profile.html'


#urls.py
urlpatterns = [
    path('', HomePageView.as_view(), name='home'),
    path('signup', SignUpView.as_view(), name='signup'),
    path('login', LoginView.as_view(), name='login'),
    path('logout', logout_view, name='logout'),
    path('<username>', ProfileView.as_view(), name='profile')
]


#base.html
<ul class="dropdown-menu">
    <li><a href="{% url 'accounts:profile' user.username %}">View Profile</a></li>
    <li><a href="#">Edit Profile</a></li>
</ul>
Birk answered 29/1, 2018 at 9:13 Comment(1)
Are you sure that the user has a username? Does {% url 'accounts:profile' "bob" %} work?Chaney
R
12

You need to tell your view to use username as the lookup field. You could either do this by defining slug_field and slug_url_kwarg on the model, or by overriding get_object. For example:

class ProfileView(views.LoginRequiredMixin, generic.DetailView):
    model = models.User
    template_name = 'accounts/profile.html'
    slug_field = 'username'
    slug_url_kwarg = 'username'

The first of these determines what field to use in the model lookup; the second determines what variable to use from the URL pattern.

Renown answered 29/1, 2018 at 9:22 Comment(1)
Don't forget to accept the answer, as a sign to future searchers.Renown
P
-1

Why you don't simply change your path to:

url('(?P<username>[\w]+)', ProfileView.as_view(), name='profile')

And then in your html do this:

{% url 'accounts:profile' username=user.username %}

Another way would be to do this:

url('accounts/profile', ProfileView.as_view(), name='profile')

And in your profile template use request.user to access you user data

EDIT:

Try to override the get_object method as explained here

def get_object(self):
    return get_object_or_404(User, pk=request.session['user_id'])
Psychological answered 29/1, 2018 at 9:21 Comment(3)
This does not in any way answer the question. Plus, path does not accept a regex.Renown
Thanks for answering but it shows still same error :(Birk
i used re_path btwBirk

© 2022 - 2024 — McMap. All rights reserved.