I have been trying to solve this issue for a while and am stumped, this issue is a bit unique in a sense that the csv file that I am checking the header for is from a file upload in the forms.py. What I mean is that the csv file being checked does not exist in any directory so you can’t just open a specific file, just from my research of other solutions, they all seem to be about an existing file in a directory rather than a file upload.
So, the header must = “IP Address”, and the form will submit without an issue, when the file header is equal to ” ” or != “IP Address”, when the form gets submitted the Django debug window comes up. I am struggling with inputting a validation error or implementing a redirect.
If you have any useful links, documentation, or would like to solve, please feel free I would appreciate it a lot.
import csv
import io
import pandas as pd
from typing import Any
from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import FileExtensionValidator
from api.utils.network_utils import NetworkUtil
from .models import BlockedList
forms.py
class CSVForm(forms.Form):
csv_file = forms.FileField(required=True, validators=[FileExtensionValidator(allowed_extensions=[".csv", ".xls", "xlsx"])])
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ips_from_csv = []
def get_ips_from_csv(self):
return self.ips_from_csv
def clean_csv_file(self):
csv_file = self.cleaned_data.get("csv_file")
if not csv_file:
return
with csv_file.open() as file:
reader = csv.DictReader(io.StringIO(file.read().decode("utf-8")))
for row in reader:
form_data = self.cleaned_data.copy()
form_data["address"] = NetworkUtil.extract_ip_address(row["IP Address"])
self.ips_from_csv.append(form_data["address"])
I do know that the file extension validation is still weak as it does not check the file contents, I am doing that on my own. But where I am struggling is the clean_csv_file(self), the filefield does not exist in my models.py as I am not storing these file/uploads in any MEDIA directory.