friendsmap/map/views.py

73 lines
2.2 KiB
Python
Raw Normal View History

2019-03-02 16:17:48 +01:00
from django.contrib import messages
2019-03-02 15:53:27 +01:00
from django.contrib.auth.mixins import LoginRequiredMixin
2019-03-02 16:17:48 +01:00
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views import generic
2019-03-02 15:53:27 +01:00
2019-03-02 12:47:44 +01:00
from map import models
2019-03-02 17:39:53 +01:00
from map.forms import LocationForm
2019-03-02 16:17:48 +01:00
from map.mixins import QuickActionsMixin
2019-03-02 12:04:27 +01:00
2019-03-02 12:47:44 +01:00
2019-03-02 16:17:48 +01:00
class MapView(LoginRequiredMixin, QuickActionsMixin, generic.ListView):
2019-03-02 12:47:44 +01:00
model = models.FriendLocation
context_object_name = 'locations'
template_name = 'map/map.html'
2019-03-02 16:17:48 +01:00
def get_quick_actions(self):
2019-03-02 17:39:53 +01:00
try:
return [
{
'url': reverse_lazy('change-location', kwargs={'pk': self.request.user.location.pk}),
'category': 'secondary',
'display': f'Change your location'
},
]
except models.FriendLocation.DoesNotExist:
return [
{
'url': reverse_lazy('add-location', kwargs={'pk': self.request.user.pk}),
'category': 'secondary',
'display': f'Add your location'
},
]
2019-03-02 16:17:48 +01:00
class EditLocationView(LoginRequiredMixin, generic.UpdateView):
model = models.FriendLocation
context_object_name = 'location'
template_name = 'map/change_location.html'
fields = [
'latitude',
'longitude',
'start_date',
'end_date',
]
success_url = reverse_lazy('map')
def dispatch(self, request, *args, **kwargs):
obj = self.get_object() # type: models.FriendLocation
if obj is None or obj.friend != request.user:
messages.warning(request, "This is not your location.")
return redirect('map')
return super().dispatch(request, *args, **kwargs)
2019-03-02 17:39:53 +01:00
class AddLocationView(LoginRequiredMixin, generic.CreateView):
model = models.FriendLocation
context_object_name = 'location'
template_name = 'map/change_location.html'
success_url = reverse_lazy('map')
def get_initial(self):
initial = super().get_initial()
initial = initial.copy()
initial['friend'] = self.request.user
return initial
def get_form(self, form_class=None):
return LocationForm(self.request, **self.get_form_kwargs())