'Django : can't interrupt update function with redirect. Is it possible?

I use a function for updating a Model.

def update_mapping(request, pk):
    flow = Flow.objects.get(pk=pk)
    mappings = MappingField.objects.filter(fl_id=pk)
    headers_samples = GetCsvHeadersAndSamples(request, pk)
    [...]

In this function, I call another one (GetCsvHeadersAndSamples) for getting datas from a CSV. Later, I use those datas with JS in the template.

def GetCsvHeadersAndSamples(request, flow_id):
    get_file_and_attribs = get_csv(request, flow_id)
    file = get_file_and_attribs[0]
    separator = get_file_and_attribs[1]
    encoding = get_file_and_attribs[2]
    with open(file, newline='') as f:
        reader = csv.reader(f, delimiter=separator, 
  encoding=encoding)
        headers = next(reader)
        samples = next(itertools.islice(csv.reader(f), 1, None))
    headersAndSamples = {'headers': headers, 'samples': samples}
    return headersAndSamples

For accessing CSV datas, I use another function for checking if the CSV still exists, in which case, I retrieve datas in it.

def get_csv(request, flow_id):
    flow = Flow.objects.get(pk=flow_id)
    file = flow.fl_file_name
    separator = flow.fl_separator
    media_folder = settings.MEDIA_ROOT
    file = os.path.join(media_folder, str(file))
    if os.path.isfile(file):
        file_2_test = urllib.request.urlopen('file://' + file).read()
        encoding = (chardet.detect(file_2_test))['encoding']
        return (file, separator, encoding)
    else:
        # print('No file')
        messages.error(request, "File not found or corrupted.")
        return HttpResponseRedirect(reverse('mappings-list', args=(flow_id,)))

I hoped that the return would "break" my original function and would redirect to the 'mappings-list' page with the message.error. But it continues and returns to GetCsvHeadersAndSamples function that generates an error because CSV datas were not found. Nota: the commented print however shows well that the file is not found.

It seems that the way I'm doing things is not the good one.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source