0

I have a django views function that converts csv into another delimiter format. But, I just want to convert csv file and reject other files.

def index(request):
    csv_form = ''
    if request.method == 'POST':
        csv_form = CsvForm(request.POST, request.FILES)
        if csv_form.is_valid():
            csv_file = TextIOWrapper(request.FILES['csv_file'].file, encoding='ascii', errors='replace')
            #other actions

I cannot use the below code because this works with only binary files, but the csv module wants to have text-mode files instead. Any alternatives to proceed with only csv files.

if not csv_file.name.endswith('.csv'):
    messages.error(request, 'THIS IS NOT A CSV FILE')
Atom Store
  • 961
  • 1
  • 11
  • 35

2 Answers2

1

Depending on how secure this needs to be. The easiest step is simply to limit the extension type on the upload HTML field.

<input type="file" accept=".csv" />

Obviously, anyone could just name the extension .csv to circumnavigate but that would be the case with any solution that is just checking extensions.

Tom
  • 42
  • 6
0

You can check if there are any commas, and if there are any words between them.

Igorek
  • 35
  • 1
  • 5