1

What I m trying to do:

Upload a CSV file(Form #1) and show header of a CSV file in the dropdown (Form #2). and these forms are on the same page.

What I have tried:

for now I able to upload CSV file and display header in a webpage.

index.html

<form action="" method="POST" enctype="multipart/form-data">
                {% csrf_token %}
                <div class="form-group">
                    <label for="file1">Upload Files</label>
                    <div class="custom-file">
                    <input type="file" accept=".csv" id="file1" name="file"  required="True" class="form-control custom-file-input">
                    <label class="custom-file-label" for="file1"></label>
                    </div>
                </div>
                <div class="form-group d-flex justify-content-center">
                    <button type="submit" class="btn text-white w-50" value="Upload">Upload</button>
                </div>
            </form>

views.py

def read_csv(request):
    csv_file = request.FILES['file']
    data = pd.read_csv(csv_file)
    i = list(data.head(0))
    context = {'loaded_data': i}
    return render(request, "WebApp/index.html", context)
Sandeep Sharma
  • 639
  • 2
  • 9
  • 34

2 Answers2

0

You can use AJAX request to handle this. You can check this answer, which has a sample AJAX request. In the views.py file, you can handle the request by checking request.is_ajax() and return the context you produce from CSV file via JsonResponse. At the success part of the AJAX call, you can manipulate the dropdown DOM element. There is a good tutorial here. If you are not familiar with these, feel free to ask about the parts you are confused.

Deniz Kaplan
  • 1,549
  • 1
  • 13
  • 18
0

So data was in a list I just have to loop through <option>:

<select class="custom-select" id="inputGroupSelect01">
   {% for x in loaded_data %}
      <option value="{{ x }}">
             {{ x }}
      </option>
   {% endfor %}
</select>
Sandeep Sharma
  • 639
  • 2
  • 9
  • 34