Reputation: 41
I'm using the UpdateView class to allow users to update their content in my app. I am now trying to figure out how to allow users to only edit their own content (and not other users' content). Appreciate any help.
class OrganismUpdate(UpdateView):
model = Organism
fields = ['name', 'edibility', 'ecosystem', 'weather', 'date', 'location']
template_name_suffix = '_update_form'
success_url ="/organism_images"
Upvotes: 1
Views: 189
Reputation: 330
You can use the UserPassesTestMixin
class, so the user will only able to update hhis/heer profile
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
class OrganismUpdate(UpdateView, UserPassesTestMixin):
model = Organism
fields = ['name', 'edibility', 'ecosystem', 'weather', 'date', 'location']
template_name_suffix = '_update_form'
success_url ="/organism_images"
def form_valid(self,form):
form.instance.user= self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user== organism.user:
return True
return False
Upvotes: 1
Reputation: 41
After narrowing down my question, I found an answer already on stackoverflow.
https://stackoverflow.com/a/8595758/14263621
Upvotes: 0