Issue
I am new to Python . I am trying to create a webapp from Django which will read data from Excel file and then it will show that data on webpage in a form of dropdown .
This is the structure of my web app which is I am creating
I have also created a python script which is parsing the excel data and returning the json data
import pandas
import json
# Read excel document
excel_data_df = pandas.read_excel('Test-Data.xlsx', sheet_name='Sheet1')
# Convert excel to string
# (define orientation of document in this case from up to down)
thisisjson = excel_data_df.to_json(orient='records')
# Print out the result
print('Excel Sheet to JSON:\n', thisisjson)
thisisjson_dict = json.loads(thisisjson)
with open('data.json', 'w') as json_file:
json.dump(thisisjson_dict, json_file)
This is output of this script
[{"Name":"Jan","Month":1},{"Name":"Feb","Month":2},{"Name":"March","Month":3},{"Name":"April","Month":4},{"Name":"May","Month":5},{"Name":"June","Month":6},{"Name":"July","Month":7},{"Name":"August","Month":8},{"Name":"Sep","Month":9},{"Name":"October","Month":10},{"Name":"November","Month":11},{"Name":"December","Month":12}]
This is what I am to have on html
<!DOCTYPE html>
<html>
<body>
<h1>The select element</h1>
<p>The select element is used to create a drop-down list.</p>
<form action="">
<label for="months">Choose a Month:</label>
<select name="months" id="month">
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">March</option>
<option value="4">April</option>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Now where I am stuck is how we can integrate this in my webapp and how we can use this Json data to create a dropdown list on my webpage.
Solution
You need to do following 3 steps.
- Write a view function to see your Excel data in your HTML.
- Add your view function in your urls.py file.
- Create a loop in your HTML to see your months_data.
1. my_website/views.py
from django.http import Http404
from django.shortcuts import render
def get_months(request):
months_data = your_json
return render(request, 'your_html_path', {'months': months_data})
2. my_website/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.get_months),
]
3. home.html
<!DOCTYPE html>
<html>
<body>
<h1>The select element</h1>
<p>The select element is used to create a drop-down list.</p>
<form action="">
<label for="months">Choose a Month:</label>
<select name="months" id="month">
{% for month in months %}
<option value={{ month.Month }}>{{ month.Name }}</option>
{% endfor %}
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Also, you can look for more information about views Writing views | Django documentation
and you can look for more information about urls URL dispatcher | Django documentation
I hope it works for you!
Answered By - Ahmet Deger
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.