Raise error for when there is no header matching the specified row name from CSV

The issue is that when user clicks upload csv and picks a file and tries to submit the file. If the header of the file is not equal to "IP Address", then I get the debug menu from Django. The CSV file does not exist in any directory, so it is handled via upload, I was wondering what's best practice for raising an error, I have tried some methods below but still get the debug menu.

This is the forms.py class that handles the CSV form.

class CSVForm(forms.Form):
    csv_file = forms.FileField(required=True)

    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:
        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"])

That is what currently works, below is the code that I have tried to implement, but I am no sure how to handle the error side of things.

if form_data["address"] != row["IP Address"]:

and this

with open(file, "r") as inf:
     csv_reader = csv.DictReader(inf)
     for header in csv_reader:
         if header != row["IP Address"]:
Back to Top