Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django UpdateView without pk in the url

I am using Django's UpdateView to update a user's profile. I pass the pk of the profile in the url like the following:

url(r'^profile/edit/(?P<pk>(\d+))$', profileviews.ProfileUpdateView.as_view(),

and in the view.py, I just use the UpdateView:

class ProfileUpdateView(UpdateView):
    model = Profile
    form_class = UserProfileForm

It can work. However, I find that if I login as ANOTHER user and type in the same url, I will be able to edit this user's profile! This is definitely wrong and by no means should another user have access to editing others' profile.

May I know if there are very good solutions to solve this problem? Hiding pk in url? Or other better solutions?

Thank you so much.

like image 865
Wei Xu Avatar asked Aug 31 '25 05:08

Wei Xu


1 Answers

URLs

# ... omitted
    url(r'^profile/edit/$', profileviews.ProfileUpdateView.as_view(),
# ... omitted

Views

class ProfileUpdateView(UpdateView):
    model = Profile
    form_class = UserProfileForm

    def get_object(self):
        """
        Returns the request's user.
        """
        return self.request.user.get_profile()

    # Then (unrelated, but for security)
    dispatch = login_required(UpdateView.dispatch)
like image 53
orokusaki Avatar answered Sep 02 '25 20:09

orokusaki