views.py 1.69 KB
Newer Older
okhin's avatar
okhin committed
1
import json
Okhin's avatar
Okhin committed
2
import csv
okhin's avatar
okhin committed
3

Okhin's avatar
Okhin committed
4
from django.http import HttpResponse
okhin's avatar
okhin committed
5
from django.views.decorators.csrf import csrf_exempt
Okhin's avatar
Okhin committed
6
from django.contrib.contenttypes.models import ContentType
7 8
from rest_framework import viewsets
from rest_framework.response import Response
9

10 11
from picampaign.feedback.serializers import FeedbackSerializer
from picampaign.feedback.models import Feedback, FeedbackCategory
okhin's avatar
okhin committed
12
from picampaign.contact.models import Contact
13 14 15 16 17 18 19


class FeedbackViewSet(viewsets.ViewSet):

    queryset = Feedback.objects.all()
    serializer_class = FeedbackSerializer

okhin's avatar
okhin committed
20
    @csrf_exempt
21
    def create(self, request, campaign_pk=None):
okhin's avatar
okhin committed
22
        serializer = FeedbackSerializer(data=request.data)
okhin's avatar
okhin committed
23 24 25 26 27 28
        try:
            serializer.is_valid(raise_exception=True)
            feedback = serializer.create(serializer.validated_data)
            return Response(feedback.id)
        except Exception as e:
            raise e
Okhin's avatar
Okhin committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50


def FeedbackExportCSVView(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="feedbacks.csv"'

    model = ContentType.objects.get_for_id(int(request.GET['ct']))
    feedbacks = model.model_class().objects.filter(
            pk__in=[int(pk) for pk in request.GET['ids'].split(',')]).select_related(
                    'callee', 'callee__contact', 'callee__campaign', 'category')

    writer = csv.writer(response)
    # A Header is nice
    writer.writerow(['Date', 'Contact', 'Campaign', 'Category', 'Comment'])
    for feedback in feedbacks:
        writer.writerow([feedback.date,
            feedback.callee.contact.full_name,
            feedback.callee.campaign,
            feedback.category,
            feedback.comment])

    return response