Skip to content
Advertisement

Django writing generic update view restricted to certain user

I am building a small blog using django.I want to build a function that allow post author to delete and update their own posts. Then I find django has LoginMixin for generic view,but it only block those who don’t login.

My article Model is like below

JavaScript

This is the generic article detail view.

JavaScript

I firstly want to add something like this in the detail template:

JavaScript

Then I realize that this just hides the a tag ,it can’t stop other users to touch the update url simply change the url.

Is there anyway in django can restricted the update and delete permissions to the original user by simply using generic view?Even if they directly enter the update url,they will be rejected.

Advertisement

Answer

Override get_queryset in your UpdateView, so that the user can only access items that they authored. Use the LoginRequiredMixin to ensure that only logged-in users can access the view.

JavaScript

In the template, I would compare the author_id with the user’s primary key to decide whether to show the link or not.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement