diff --git a/lostplaces/lostplaces_app/views.py b/lostplaces/lostplaces_app/views.py index 9f0e1c9..d6e9fa6 100644 --- a/lostplaces/lostplaces_app/views.py +++ b/lostplaces/lostplaces_app/views.py @@ -19,10 +19,27 @@ from .models import Place, PlaceImage, Voucher # Create your views here. -# BaseView that checks if user is logged in +# BaseView that checks if user is logged in. class IsAuthenticated(LoginRequiredMixin, View): redirect_field_name = 'redirect_to' +# BaseView that checks if logged in user is submitter of place. +class IsSubmitter(UserPassesTestMixin, View): + def test_func(self): + """ Check if user is eligible to modify place. """ + if self.request.user.is_superuser: + return True + + # Check if currently logged in user was the submitter + place_obj = self.get_object() + + if self.request.user == place_obj.submitted_by: + return True + + messages.error( + self.request, 'You do not have permission to do this.') + return False + class SignUpView(CreateView): form_class = ExplorerCreationForm success_url = reverse_lazy('login') @@ -45,7 +62,7 @@ class HomeView(View): } return render(request, 'home.html', context) -class PlaceUpdateView(IsAuthenticated, UpdateView): +class PlaceUpdateView(IsAuthenticated, IsSubmitter, UpdateView): template_name = 'place/place_update.html' model = Place form_class = PlaceForm @@ -101,22 +118,8 @@ class PlaceCreateView(IsAuthenticated, View): ) place_image.save() -class PlaceDeleteView(IsAuthenticated, UserPassesTestMixin, DeleteView): +class PlaceDeleteView(IsAuthenticated, IsSubmitter, DeleteView): template_name = 'place/place_delete.html' model = Place success_url = reverse_lazy('place_list') - - def test_func(self): - """ Check if user is eligible to delete place. """ - if self.request.user.is_superuser: - return True - - # Check if currently logged in user was the submitter - place_obj = self.get_object() - - if self.request.user == place_obj.submitted_by: - return True - - messages.error( - self.request, 'You do not have permission to delete this place.') - return False \ No newline at end of file + \ No newline at end of file