Hanze_Surfnet_Data_POC/Enquete/enquete/apps/vragenlijst/views.py
2022-02-17 14:35:54 +01:00

70 lines
2.9 KiB
Python

from django.http import HttpResponseRedirect
from django.shortcuts import render
from .models import Questionnaire, QuestionnaireResponse, QuestionnaireStorage
from django.conf import settings
from django.contrib import messages
import csv
from uuid import uuid4
from pathlib import Path
from storage.storage import Storage
# Create your views here.
def index(request):
# latest_question_list = Question.objects.order_by('-pub_date')[:5]
questionnaires = Questionnaire.objects.order_by('name')
context = {'questionnaires': questionnaires}
return render(request, 'vragenlijst/index.html', context)
def questionnaire(request, questionnaire_id):
if request.method == 'POST':
# As we should have a Django form, we could use te form validator. For now, everyhing is valid ;)
questionnaire = Questionnaire.objects.get(pk=questionnaire_id)
# Get all the questions in one list with a single query
allQuestions = {}
for question in list(questionnaire.allQuestions.order_by('order').values('id','name')):
allQuestions[str(question['id'])] = question['name']
# Store the response as a ';' seperated CSV file in order of the questionaire questions order
try:
csv_file = Path(f'{settings.HANZE_TEMP_CSV_STORAGE}/{questionnaire.name}-{uuid4()}.csv')
with open(csv_file, 'w') as csvfile:
filewriter = csv.writer(csvfile, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
# Add headers
filewriter.writerow(['vraag', 'antwoord'])
for question in allQuestions:
if request.POST.get(question):
filewriter.writerow([allQuestions[question], request.POST[question]])
# Store the data also in a database
QuestionnaireResponse(questionnaire=questionnaire, response=csv_file.read_text()).save()
storageSettings = QuestionnaireStorage.objects.first()
# Move data to external storage
webdav = Storage(
storage_type=storageSettings.type,
url=storageSettings.server,
username=storageSettings.username,
password=storageSettings.password
)
webdav.upload_file(source=csv_file, destination=f'{storageSettings.path}/{csv_file.name}')
messages.success(request, 'Questionaire is saved to disk.')
except Exception as ex:
messages.error(request, f'Could not save the questionaire. Error: {ex}')
# Redirect to starting point
return HttpResponseRedirect('/vragenlijst/')
questionnaire = Questionnaire.objects.get(pk=questionnaire_id)
context = {'questionnaire': questionnaire, 'menu_width': 100 / questionnaire.topics.count()}
return render(request, 'vragenlijst/form.html', context)