ojuso-map/apps/files/views.py
2019-08-20 00:10:20 +02:00

59 lines
1.5 KiB
Python

from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import PermissionDenied
from django.http import JsonResponse
from django.views.generic import DetailView
from django.views.generic import FormView
from .forms import FileForm
from .forms import ImageFileForm
from .models import File
from .models import ImageFile
class FileUploadView(LoginRequiredMixin, FormView):
model = File
form_class = FileForm
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return JsonResponse(
{
"is_valid": True,
"url": self.object.file.url,
"name": self.object.file.name,
"id": self.object.pk,
}
)
def form_invalid(self, form):
return JsonResponse({"is_valid": False, "errors": form.errors})
class ImageFileUploadView(FileUploadView):
model = ImageFile
form_class = ImageFileForm
class FileDeleteView(LoginRequiredMixin, DetailView):
model = File
def get(self, request, *args, **kwargs):
return self.post(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.object = self.get_object()
if request.user != self.object.user:
raise PermissionDenied
self.object.delete()
return JsonResponse({"success": True})
class ImageFileDeleteView(FileDeleteView):
model = ImageFile