lostplaces-backend/lostplaces/lostplaces_app/views/views.py

80 lines
2.9 KiB
Python

from django.views import View
from django.views.generic.edit import CreateView
from django.views.generic.detail import SingleObjectMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib import messages
from django.urls import reverse_lazy
from django.shortcuts import render, redirect
from lostplaces_app.forms import ExplorerCreationForm
from lostplaces_app.models import Place, PhotoAlbum
from lostplaces_app.views.base_views import IsAuthenticated, IsPlaceSubmitter
class SignUpView(SuccessMessageMixin, CreateView):
form_class = ExplorerCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
success_message = 'User created.'
class HomeView(View):
def get(self, request, *args, **kwargs):
place_list = Place.objects.all().order_by('-submitted_when')[:10]
place_map_center = Place.average_latlon(place_list)
context = {
'place_list': place_list,
'place_map_center': place_map_center
}
return render(request, 'home.html', context)
class PhotoAlbumCreateView(IsAuthenticated, SuccessMessageMixin, CreateView):
model = PhotoAlbum
fields = ['url', 'label']
template_name = 'photo_album/photo_album_create.html'
success_message = 'Photo Album submitted'
def get(self, request, place_id, *args, **kwargs):
self.place = Place.objects.get(pk=place_id)
return super().get(request, *args, **kwargs)
def post(self, request, place_id, *args, **kwargs):
self.place = Place.objects.get(pk=place_id)
response = super().post(request, *args, **kwargs)
self.object.place = self.place
self.object.submitted_by = request.user
self.object.save()
return response
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['place'] = self.place
return context
def get_success_url(self):
return reverse_lazy('place_detail', kwargs={'pk': self.place.id})
class PhotoAlbumDeleteView(IsAuthenticated, IsPlaceSubmitter, SingleObjectMixin, View):
model = PhotoAlbum
pk_url_kwarg = 'pk'
success_message = 'Photo Album deleted'
def get_place(self):
place_id = self.get_object().place.id
return Place.objects.get(pk=place_id)
def test_func(self):
can_edit_place = super().test_func()
if can_edit_place:
return True
if self.get_object().submitted_by == self.request.user:
return True
messages.error(self.request, 'You do not have permissions to alter this photo album')
return False
def get(self, request, *args, **kwargs):
place_id = self.get_object().place.id
self.get_object().delete()
messages.success(self.request, self.success_message)
return redirect(reverse_lazy('place_detail', kwargs={'pk': place_id}))