You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.6 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. import csv
  2. from io import TextIOWrapper
  3. from django.urls import reverse
  4. from django.http import HttpResponse, HttpResponseRedirect
  5. from django.shortcuts import get_object_or_404
  6. from django.views import View
  7. from django.views.generic import TemplateView, CreateView
  8. from django.views.generic.list import ListView
  9. from django.contrib.auth.mixins import LoginRequiredMixin
  10. from .permissions import SuperUserMixin
  11. from .forms import ProjectForm
  12. from .models import Document, Project
  13. class IndexView(TemplateView):
  14. template_name = 'index.html'
  15. class ProjectView(LoginRequiredMixin, TemplateView):
  16. def get_template_names(self):
  17. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  18. return [project.get_template_name()]
  19. class ProjectsView(LoginRequiredMixin, CreateView):
  20. form_class = ProjectForm
  21. template_name = 'projects.html'
  22. class DatasetView(SuperUserMixin, LoginRequiredMixin, ListView):
  23. template_name = 'admin/dataset.html'
  24. paginate_by = 5
  25. def get_queryset(self):
  26. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  27. return project.documents.all()
  28. class LabelView(SuperUserMixin, LoginRequiredMixin, TemplateView):
  29. template_name = 'admin/label.html'
  30. class StatsView(SuperUserMixin, LoginRequiredMixin, TemplateView):
  31. template_name = 'admin/stats.html'
  32. class DataUpload(SuperUserMixin, LoginRequiredMixin, TemplateView):
  33. template_name = 'admin/dataset_upload.html'
  34. def post(self, request, *args, **kwargs):
  35. project = get_object_or_404(Project, pk=kwargs.get('project_id'))
  36. try:
  37. form_data = TextIOWrapper(request.FILES['csv_file'].file, encoding='utf-8')
  38. reader = csv.reader(form_data)
  39. for line in reader:
  40. text = line[0]
  41. Document(text=text, project=project).save()
  42. return HttpResponseRedirect(reverse('dataset', args=[project.id]))
  43. except:
  44. return HttpResponseRedirect(reverse('dataset-upload', args=[project.id]))
  45. class DataDownload(SuperUserMixin, LoginRequiredMixin, View):
  46. def get(self, request, *args, **kwargs):
  47. project_id = self.kwargs['project_id']
  48. project = get_object_or_404(Project, pk=project_id)
  49. docs = project.get_documents(is_null=False).distinct()
  50. filename = '_'.join(project.name.lower().split())
  51. response = HttpResponse(content_type='text/csv')
  52. response['Content-Disposition'] = 'attachment; filename="{}.csv"'.format(filename)
  53. writer = csv.writer(response)
  54. for d in docs:
  55. writer.writerows(d.make_dataset())
  56. return response