I used a class based view to update a user profile using this code
class EditProfileViewClass(generic.UpdateView):
model = UserProfile
fields = ['bio', 'profile pic']
template_name = 'users/update.html'
success_url = reverse_lazy('home')
path('profile/<int:pk>/update', EditProfileViewClass.as_view(), name="profile"),
<a href="{% url 'profile' user.id %}">Your Profile</a>
the issue right now is, Instead of having the url like the one above, I want it to be like
path('profile/<str:username>/update', EditProfileViewClass.as_view(), name="profile"),
but unfortunately I get an attribute error saying:
Generic detail view EditProfileView must be called with either an object pk or a slug in the URLconf.
So I tried making a function based view so I can get the "username" from the url, doing that didn't allow me to get the form I needed to update the specific username.
Any help would be great. Thanks.
CodePudding user response:
In your EditProfileViewClass
view you can add pk_url_kwarg
or slug_url_kwarg
.
class EditProfileViewClass(UpdateView):
model = UserProfile
fields = ['bio', 'profile pic']
template_name = 'users/update.html'
success_url = reverse_lazy('home')
pk_url_kwarg = 'username'
slug_url_kwarg = 'username'
CodePudding user response:
You can use a class-based view, you only need to update the the slug_field
(which determines on what should be used), and the slug_url_kwargs
:
class EditProfileViewClass(UpdateView):
model = UserProfile
fields = ['bio', 'profile_pic']
template_name = 'users/update.html'
success_url = reverse_lazy('home')
slug_field = 'user__username'
slug_url_kwarg = 'username'
This will thus take the username
parameter of the URL, and it will filter the queryset to only retrieve a UserProfile
that is linked to a user
with that username
.