How to render json data in Python Django App - python

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.

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!

Why dump to json?
Use pyexcel its easy to understand the docs.
link docs
Another option is to use ajax, you can implement the excel output (json Response) in a simple way in your template. If you dont want to use pyexcel (which is in most cases sufficient) let me know, then we can get into an ajax example.

I'm not sure if you're using function or class based view, but pass your data in the context
...
context['months'] = [{"Name":"Jan","Month":1}, ...]
...
Then in the template iterate over it
...
{% for item in months %}
<select name="months" id="month">
<option value="{{ item.Month }}">{{ item.Name }}</option>
</select>
{% endfor %}
...

Related

How do I get user input from search bar to display in a page? Django

Django is very challenging and I still need to get used to the code and currently, I just want the search bar to display every time a user input a text and it will display like a title I really don't how to interpret the code to tell that every time the user inputs in the search bar, It is supposed to display the user input on a page like a title.
Example: user input in the search bar: cat and it displays cat title
Display on the current page:
Result search: "Cat"
HTML Code
<!-- Search Bar -->
<form action="{% url 'enc:search' %}" method="GET">
{% csrf_token %}
<input class="search" type="text" name="q" placeholder="Search">
</form>
In my views.py I only write this code and I don't know what to write it.
views.py
def search (request):
title = request.GET.get("q", "")
urls.py
urlpatterns = [
path("", views.index, name="index"),
path("search/", views.search, name="search"),
Right now just a simple display from the search bar input later I will code it in a data search where there is some file to integrate the search but right now I really need some help my brain is cracking. It's kinda sad I mean I know it be a simple code but I don't know why I can't figure it out.
please do help me if you have tips on how to be better on Django and python too it be much help for me and thank you for your time I really appreciate it very much.
searchpage.html :
<!-- Search Bar -->
<form action="{% url 'enc:search' %}" method="POST">
{% csrf_token %}
<input class="search" type="text" name="q" placeholder="Search">
<input type="submit" value="Submit">
</form>
views.py:
from django.shortcuts import render
def search (request):
#defines what happens when there is a POST request
if request.method == "POST":
title = request.POST.get("q")
return render(request,'new_template.html', { 'title' : title })
#defines what happens when there is a GET request
else:
return render(request,'searchpage.html')
new_template.html:
<!DOCTYPE html>
{% load static %}
<html>
<head>
<title>search term</title>
</head>
<body>
<h1> {{ title }} </h1>
</body>
</html>

Redirecting buttons with values to other django templates/views

Firstly, I am getting a csv file from the user.
(Template file:)
<form method="post" action="{% url 'rowcol' %}" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file" accept=".csv">
<button type="submit">Upload File</button>
</form>
Then i am generating a list of all the columns present in the file and then calling another html file. (views.py:)
def rowcol(request):
if request.method == 'POST':
file = request.FILES['file']
dataset=pd.read_csv(file)
lst=list(dataset)
return render(request, 'Link5_rc.html', {'arr':lst})
return HttpResponse('')
In that html file, i am creating buttons for all the columns present.(Link5_rc.html:)
{% for link in arr %}
<form action=" " method="post">
<button name="{{link}}" type="submit" value="{{link}}">{{link}}</button>
</form>
{% endfor %}
Now the following is the part where i am stuck: I want these buttons to redirect to another html page or maybe a view in views.py , where i can show to the user which column he/she selected and then perform further actions on that particular column.
You can pass one or more values to the request as in the following example:
Some text
You can use variables like:
Some text
In your app urls.py you should set the following to receive the extra data in the request:
url(r'^your_name/(?P<value_1>[\d\D]+)$', views.your_view, name="your_url_alias")
Then, in your view function you should receive the data as in:
def your_view(request, value_1):
An then you can use the value to filter the queryset.

Django: Use text box data and write that text in a file

I am super new to Django and web development. Right now my objective is to create a google like interface and take the text from search box and write it to a file (in other words just want to access text data in the search box). I have created a search page like below
search.html
{% extends "header.html" %}
{% block content %}
<div style="display: flex; justify-content: center;">
<img src="/static/images/logo.jpg" class="responsive-img" style='max-height:300px;' alt="face" >
</div>
<form method="get" action="">
{% csrf_token %}
<div style="display: flex; justify-content: center;">
<input type="text" name="query" placeholder="Search here..." required size="70" >
<button type="submit">Go!</button>
</div>
<button type="submit">Search</button>
</form>
{% endblock %}
views.py
from django.shortcuts import render
def index(request):
return render(request, 'search.html')
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index')
]
Please give me a hint/example of how to go forward from here ? Thanks.
Your search field looks like this:
<input type="text" name="query">
The name of the input is query. Since it's a GET form, when you submit it, you must have noticed, the url looks something like this:
/?query=<value of the input>
The part after ? is called querystring. For every request, Django maintains a dictionary of the querystring. The request object has a dictionary called GET for GET requests. If you make a POST request, Django will save the form data in a dict called POST.
To access the value of the request querystring in Django, you can do this:
query = request.GET.get('query')
If it's a POST request, you'd do the same but use the POST dictionary this time:
some_value = request.POST.get('some_key')
Full docs on this can be found at - Request and response objects.
This should do it
views.py
def index(request):
query = request.GET.get('query')
# do a check here to make sure search_term exists before attempting write
with open('/path/to/file', 'rw') as f:
f.write(query)
return render(request, 'search.html')

Django - POST get options from select

I have a html form that looks like this.
{% url 'myapp:myapp_submit' as submit %}
<form name='main' method="POST" action={{submit}}>
{% csrf_token %}
<select class='form-control' size=10 id="test" name='test' multiple>
<option>Test</option>
</select>
<input type="submit"/>
</form>
and url.py
from . import views
app_name = 'myapp'
urlpatterns = [
url(r'^$', views.myapp, name='myapp'),
url(r'results/$', views.myapp_submit, name='myapp_submit')
]
and views.py
def myapp_submit(request):
print request.POST
The only thing I get back is
<QueryDict: {u'csrfmiddlewaretoken'...]}>
How do I get back the options held in the select tag? I would use the model/view form here but I'm doing some very crazy things with JS to constantly update the options available.
UPDATE
I have used:
request.POST.getlist('test')
But it will only return ['Test'] If I highlight it with my mouse. I simply want all the options under the select tag. ex.
<select class='form-control' size=10 id="test" name='test' multiple>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
<option>Test4</option>
</select>
and
###Not sure if it's still getlist method
>>request.POST.getlist('test')
['Test','Test2','Test3','Test4']
Try to change your views.py:
def myapp_submit(request):
request.POST.getlist('test[]')
Because you say you're doing weird things with Js, you can first check the POST request from your browser and what parameters you send with it.
A month ago I solved this problem, you need to use name in your option tag
Example:
<select name="status">
<option name="status">
and see result in your view.

Django can't process html form data

I have a simple Django site and I want to pass data from the first box, and return that value plus 5 to the second form box on the page. I later plan on doing math with that first value but this will get me started. I am having a lot of trouble retrieving the form data. I know I need to create a function in my views.py file to process the form, and I need to put something in URLs.py to retrieve the form data. I have tried everything in tutorials, etc, but can't figure it out.
My html template is a simple page that has a form with two fields and a submit button. Django runserver pulls up the html page just fine. Here is my code:
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django import forms
def index(request):
return render(request, 'brew/index.html')
#Here I want a function that will return my form field name="input",
#and return that value plus 5 to the form laveled name="output".
#I will later us my model to do math on this, but I cant get
#this first part working
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
Here is my html template, index.html:
<html>
<head>
<title>Gravity Calculator</title>
</head>
<body>
<h1>Gravity Calculator</h1>
<p>Enter the gravity below:</p>
<form action="/sendform/" method = "post">
Enter Input: <br>
<input type="text" name="input"><br>
<br>
Your gravity is: <br>
<input type="text" name="output" readonly><br>
<br>
<input type="submit" name="submit" >
</form>
</body>
</html>
You will need to populate the result to context variable which the template can access.
view:
def index(request):
ctx = {}
if request.method == 'POST' and 'input' in request.POST:
ctx['result'] = int(request.POST.get('input', 0)) + 5
return render(request, 'brew/index.html', ctx)
then in your template:
<html>
<head>
<title>Gravity Calculator</title>
</head>
<body>
<h1>Gravity Calculator</h1>
<p>Enter the gravity below:</p>
<form action="/sendform/" method = "post">
Enter Input: <br>
<input type="text" name="input"><br>
<br>
Your gravity is: <br>
<input type="text" name="output" value="{{ result }}" readonly><br>
<br>
<input type="submit" name="submit" >
</form>
</body>
</html>
Looks like you are quite new at Django, I recommend:
use method based views, until you are comfortable with it, then
start using class based views, advantage being code reusability, but ultimately class based views spits out view methods, a good
reference site is ccbv.co.uk
using form class

Categories