Skip to content
Snippets Groups Projects
views.py 2.19 KiB
Newer Older
Neda Moeini's avatar
Neda Moeini committed
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)