Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import csv
from django.views.generic.edit import FormView
from django.urls import reverse_lazy
from django.http import JsonResponse
from .forms import CSVUploadForm
class CSVUploadView(FormView):
template_name = 'templates/upload.html'
form_class = CSVUploadForm
success_url = reverse_lazy('upload-file')
def get_context_data(self, **kwargs):
"""
This method is called when rendering the form (GET request).
"""
context = super().get_context_data(**kwargs)
context['error'] = None # No error message on GET request
context['message'] = None # No success message on GET request
return context
def form_valid(self, form):
"""
This method is called when the form is valid (POST request).
It handles the CSV validation and passes appropriate error or success messages to the template.
"""
file_obj = form.cleaned_data['file']
try:
# Read and decode the CSV file
csv_file = file_obj.read().decode('utf-8').splitlines()
reader = csv.DictReader(csv_file)
# Example validation: Check for required columns
# TODO: Add the validation logic here. This is just a sample.
required_columns = ['name']
missing_columns = [col for col in required_columns if col not in reader.fieldnames]
if missing_columns:
# If there are missing columns, return error message as JSON
return JsonResponse(
{'status': 'error', 'errors': [f"Missing columns: {', '.join(missing_columns)}"]}, status=400
)
return JsonResponse({'status': 'success', 'message': "CSV file is valid"})
except Exception as e:
# If there's an error (e.g., invalid file content), return the error message as JSON
return JsonResponse({'status': 'error', 'errors': [str(e)]}, status=400)
def form_invalid(self, form):
"""
This method is called when the form is invalid (e.g., wrong file type).
It renders the form again with errors.
"""
return JsonResponse({'status': 'error', 'errors': [form.errors]}, status=400)