Pandas corelation in Django - python

guys i am a beginner in programming and I desperately need your help. I am trying to develope a webapp using Django. I have created a HTML form in my index.html file. In my views.py I am trying to use the corr() fundtion of Pandas but every time it says Empty DataFrame
index.html
<form id='form' name='form' method="post" action="">
{% csrf_token %}
<div class="row">
<div class="form-group col-md-2">
<label for="Col 1">col 1</label>
<input type="text" class="form-control" id="col1" name="col1">
</div>
<div class="form-group col-md-2">
<label for="Col 2">col 2</label>
<input type="text" class="form-control" id="col2" name="col2">
</div>
</div>
<div class="row">
<div class="form-group col-md-2">
<label for="Col 3">col 3</label>
<input type="text" class="form-control" id="col3" name="col3">
</div>
<div class="form-group col-md-2">
<label for="Col 4">col 4</label>
<input type="text" class="form-control" id="col4" name="col4">
</div>
</div>
<button class="btn btn-primary" id='predict' name='predict'>Run forecast</button>
</form>
views.py
def index(request):
if request.method == "POST":
col1 = request.POST.get('col1')
col2 = request.POST.get('col2')
col3 = request.POST.get('col3')
col4 = request.POST.get('col4')
data = {'X':[col1, col2], 'Y':[col3, col4]}
df = pd.DataFrame(data)
x = df.corr()
print(x)
return render(request, 'corelation.html')
else:
return render(request,'index.html')
Every time I run this code it returns Empty DataFrame in terminal. However if I replace col1, col2 with actual numbers it shows the desired result.

First check that those GET variables are not empty or not numbers.
Then try to use the float cast method like float(col1)

Related

How to check if which radio button is selected using django

I have 5 radio buttons and each have different values but as user can only select 1 option out of 5 and after selecting the value of radio button should be stored in my django models.
This is my html code
<div class="col">
<div class="form-group">
<input class="form-check-input" type="radio" name="reason" id="reason1" checked>
<label class="form-check-label" for="reason1">
Casual Leave
</label>
</div>
<div class="form-group">
<input class="form-check-input" type="radio" name="reason" id="reason2">
<label class="form-check-label" for="reason2">
Medical Leave
</label>
</div>
<div class="form-group">
<input class="form-check-input" type="radio" name="reason" id="reason3">
<label class="form-check-label" for="reason3">
Earned Leave
</label>
</div>
<div class="form-group">
<input class="form-check-input" type="radio" name="reason" id="reason4">
<label class="form-check-label" for="reason4">
Office Duty
</label>
</div>
<div class="form-group">
<input class="form-check-input" type="radio" name="reason" id="reason5">
<label class="form-check-label" for="reason5">
Compensatory Off
</label>
</div>
</div>
*this code contains form tag
My Django function
def leaveapplicationsubmit(request):
if request.method == 'POST':
reason1 = request.POST['reason1']
reason2 = request.POST['reason2']
reason3 = request.POST['reason3']
reason4 = request.POST['reason4']
reason5 = request.POST['reason5']
if 'reason1' in request.POST:
reason = "Casual Leave"
elif 'reason2' in request.POST:
reason="Medical Leave"
elif 'reason3' in request.POST:
reason="Earned Leave"
elif 'reason4' in request.POST:
reason="Office Duty"
elif 'reason5' in request.POST:
reason="Compensatory Off"
else:
return HttpResponse('Please select the reason')
else:
return HttpResponse("Failed")
Please help me with it, I really need that
All of the buttons have name="reason". That is the name you should look for in the code, not reason1, reason2 etc. Those are ids, not names.
Also, each button needs a value attribute, so you can tell which one was pressed.
Look at the examples here https://www.w3schools.com/tags/att_input_type_radio.asp
In views write this code, here reason_ will hold the value which will be selected by the user and in HTML code write it as given here https://www.w3schools.com/tags/att_input_type_radio.asp then reason_ will hold the value of the selected option
def radio(request):
if request.method == "POST":
d = request.POST
for key,value in d.items():
if key == "reason":
reason_ = value

How to have single view for multiple HTML forms - Django

This is my view.So I want to keep 2 different HTML forms in same view ,But I am unable to do so beacuse whenever I add 1 form , I get the error of other on being none.
def home(request):
name = None
if request.method == 'POST':
name = request.POST.get('name')
choices = request.POST.get('choices')
subtest = request.POST.get('subtest')
reference = request.POST.get('reference')
unit = request.POST.get('unit')
test = Test()
test.name = name
test.save()
subtest = Subtest()
subtest.test = Test.objects.get(name=choices)
subtest.name = subtest
subtest.unit = unit
subtest.reference_value = reference
subtest.save()
# print(name)
return redirect('home')
return render(request,'main.html',{})
I have got 2 different forms . I didn't use django forms because I wanted to try something new.
MY FIRST FORM
<form method="POST">
{% csrf_token %}
<div class="icon-holder">
<i data-modal-target="test-popup" class="icon-cross"></i>
</div>
<div class="input-group">
<input type="text" name="name" placeholder="Test name" />
</div>
<div class="button-group">
<button type="submit">Submit</button>
</div>
</form>
MY SECOND FORM
<form method="POST">
{% csrf_token %}
<div class="icon-holder">
<i data-modal-target="menu-test-popup" class="icon-cross"></i>
</div>
<div class="input-group">
<label for="test-select">Test Name:</label>
<select name="choices" id="test-select">
{% for test in test %}
<option value="{{test.name}}" name='choices'>{{test.name|title}}</option>
{% endfor %}
</select>
</div>
<div class="input-group">
<input type="text" name="subtest" placeholder="SubTest name" />
</div>
<div class="input-group">
<input type="text" name="reference" placeholder="Reference rate" />
</div>
<div class="input-group">
<input type="text" name="unit" placeholder="Unit" />
</div>
<div class="button-group">
<button type="submit">Submit</button>
</div>
</form>
first form
<form method="POST">
...
<input name="form_type" value="first-form" type="hidden">
</form>
second form
<form method="POST">
...
<input name="form_type" value="second-form" type="hidden">
</form>
view function
def view(request):
if method == "POST":
form_type = request.POST.get('form_type')
if form_type == "first-form":
# first form's process
elif form_type == "second-form":
#second form's process
You have two forms here, when you submit the second form, only the fields from the second form gets submitted.
so from this line
name = request.POST.get('name')
name will become None. But I believe your Test model does not take any None value for name field( the reason for you " IntegrityError at / NOT NULL constraint failed: lab_test.name ").
To overcome this, first check if there is any value for 'name' then proceed with creating the test instance
if name:
test = Test()
test.name = name
test.save()
Similarly check if the other fields are present for the second form before creating and saving the instance.

Python Pyramid - Use session to pass form data to another page

I'm using Python Pyramid with Jinja2 template. I want to save my form data into session and retrieve it in another HTML page. How should I change in order to pass the data? I only know how to store the data I key in Views.py into session like this request.session['postal'] = 01934 but this is not the data I key in Delivery.jinja2. And if I used print (session['postal']), this will only show in my command prompt but not HTML page. Can anyone help me out? I'm a beginner to this.
What to add in/ change in my Views.py?
my HTML: Delivery.jinja2
<form class="form-horizontal" method="POST">
<div class="form-group">
<label class="control-label col-md-2" for="postal">Postal Code:</label>
<input type="text" class="form-control" id="postal" placeholder="Enter Postal Code" name="postal" />
</div>
<div class="form-group">
<label class="control-label col-md-2" for="address">Detailed Address:</label>
<textarea class="form-control" rows="3" id="address" placeholder="Enter Address" name="address"></textarea>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="unit">Unit No #:</label>
<input type="text" class="form-control" id="unit" placeholder="Enter Unit No" name="unit" />
</div>
<button type="submit" class="btn btn-default" name="submit">Submit</button>
</form>
Views.py
#view_config(route_name='deliveryLink', renderer='templates/deliveryLink.jinja2')
def deliveryLink(request):
print("YAY for gift delivery via Link")
if 'submit_deliverylink' in request.POST:
print("request.POST: ", request.POST)
myform = request.POST
for m in myform:
print("key: ", m, " value: ", myform[m])
session = request.session
session['postal'] = ?
session['address'] = ?
session['unit'] = ?
data = "??"
data_array = data.split(",")
session['data'] = data_array
session['delivery'] = str(data_array)
print (session['delivery'])
return HTTPFound(location='http://localhost:5555/confirmation')
return {}
#view_config(route_name='confirmation', renderer='templates/confirmation.jinja2')
def confirmation(request):
print("YAY for confirmation")
for a in request.POST:
request.session[a] = request.POST[a]
return {}
and I want the data entered previously to show on this confirmation page: Confirmation.jinja2
<form class="form-horizontal" method="POST">
<div class="form-group">
<label class="control-label col-md-2" for="postal">Postal Code:</label>
<input type="text" class="form-control" id="postal" name="postal" />
</div>
<div class="form-group">
<label class="control-label col-md-2" for="address">Detailed Address:</label>
<textarea class="form-control" rows="3" id="address" name="address"></textarea>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="unit">Unit No #:</label>
<input type="text" class="form-control" id="unit" name="unit" />
</div>
</form>
I think, you can just pass POST from initial form to template of confirmation page, without session.
If anyway you need session, you can call it from your template
<input type="text" class="form-control" id="postal" name="postal" value="{{session['postal']}}" />
# after form submitted, it sends post request, just check if it exist
if request.POST:
print("request.POST: ", request.POST)
myform = request.POST
# you need iterate over keys for this case
for m in myform.keys():
print("key: ", m, " value: ", myform[m])
session = request.session
# you can access request.POST directly or use your variable myfrom
# use myform.get('postal','') to get value by key
session['postal'] = myform.get('postal','')
session['address'] = myform.get('postal','')
session['unit'] = myform.get('unit','')
data = "??"
data_array = data.split(",")
session['data'] = data_array
session['delivery'] = str(data_array)
print (session['delivery'])
return HTTPFound(location='http://localhost:5555/confirmation')

Error of Django's forms instance

my files in project is:
djangoTry
--views.py
--forms.py
--others not included in this question files
When I click submit in my form I call this method from views.py:
from .forms import NameForm
def kontakt(request):
if request.method == 'POST':
form = NameForm(request.POST)
form.test("test")
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
phone_number = form.cleaned_data['phone_number']
email = form.cleaned_data['email']
details = form.cleaned_data['details']
return HttpResponseRedirect('/')
else:
form = NameForm()
return render(request, 'index.html', {'form':form})
NameForm is class from forms.py file:
from django import forms
class NameForm(forms.Form):
first_name = forms.CharField(label='first_name', max_length=100)
last_name = forms.CharField(label='last_name', max_length=100)
phone_number = forms.CharField(label='phone_number', max_length=100)
email = forms.CharField(label='email', max_length=100)
details = forms.CharField(label='details', max_length=100)
def test(self, message):
print("i'm in test and message is: %s " , (message))
print(self.first_name)
def is_valid(self):
print("jest valid")
return True
form.html
<form class="col s12" action="{% url 'kontakt' %}" method="post">
{% csrf_token %}
{{ form }}
<div class="row">
<div class="input-field col s6">
<input
id="first_name"
type="text"
value="hehe">
<!-- value="{{ form.first_name }}"> -->
<label for="first_name">First name</label>
</div>
<div class="input-field col s6">
<input
id="last_name"
type="text"
autocomplete="off"
value="hehe">
<!-- value="{{ form.last_name }}" > -->
<label for="last_name">Last name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="phone_number" type="number" autocomplete="off"
value="123456789">
<label for="phone_number">Phone number</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="email" type="email" autocomplete="off" value="rafald121#gmail.com" >
<label for="email">Email</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="details" type="text" autocomplete="off" value="qweqweqeq">
<label for="details">Details</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<a class="waves-effect waves-light btn">
<input id="submit" type="submit" >
<i class="material-icons right">send</i>
</a>
<!-- <input id="submit" type="submit" > -->
<label for="details">Details</label>
</div>
</div>
</form>
but everytime I get error:
AttributeError: 'NameForm' object has no attribute 'first_name'
but NameForm has "first_name" atribute
NameForm's method "test" work properly everytime but any of NameForm's variable can't be called.
Does anybody have idea what's going on ?

How can I reinsert a row using SQLAlchemy?

To add the item with the given description I use: db.session.add(new_item). To delete the item: db.session.query(Item).filter_by(item_id=new_id).delete(). To update some parts of the item: db.session.query(Item).filter_by(item_id=new_id).update({"status":"1 "}).
What should I use if I want to edit the item completely, that is, reinsert the data for the same item?
here is the code for the form:
<form class="form" action="{{ url_for('new_item') }}" method="post" role="form" enctype=multipart/form-data>
{{ form.csrf_token }}
<table>
<tr>
<td>
<div class="form-group">
<label for="item_name">item name:</label>
<input name="name" type="text" class="form-control" id="item_name">
</div>
</td>
<td>
<div class="form-group">
<label for="item_price">item price</label>
<input name="price" type="number" class="form-control" id="item_price">
</div>
</td>
<td>
<div class="form-group">
<label for="photo">Download the photo</label>
<input type="file" name="file">
<p class="help-block">Download</p>
</div>
</td>
</tr>
<tr>
<td>
<div class="form-group">
<label for="item_category">Category:</label>
<select name="category" class="form-control" id="item_category">
<option>LEGO</option>
<option>Игры_и_игрушки</option>
<option>Малыш</option>
<option>Школа_и_канцтовары</option>
<option>Творчество_и_развитие</option>
</select>
</div>
</td>
</tr>
</table>
<div class="form-group">
<label for="item_description">Description of the item:</label>
<textarea name="description" class="form-control" id="item_description" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-default">Save</button>
</form>
Here is the route for the form. There are others as well, to update the items and to delete it, but i guess this should be enough
#app.route('/admin_items', methods=['GET', 'POST'])
def admin_items():
form = AddItemForm(request.form)
available = db.session.query(Item).filter_by(status='1').order_by(Item.name.asc())
not_available = db.session.query(Item).filter_by(status='0').order_by(Item.name.asc())
return render_template('admin_items.html',
available_items=available,
not_available_items=not_available,
form=form)
#app.route('/add_item', methods=['GET', 'POST'])
#login_required
def new_item():
error = None
form = AddItemForm(request.form)
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename) and form.name.data != "" and form.description.data != "":
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOADED_ITEMS_DEST'], filename))
new_item = Item(
filename,
form.name.data,
form.description.data,
form.price.data,
form.age.data,
form.particles.data,
form.category.data,
'1',
)
db.session.add(new_item)
db.session.commit()
return redirect(url_for('admin_items'))
else:
return render_template('admin_items.html', form=form, error=error)
if request.method == 'GET':
return redirect(url_for('admin_items'))
You can specify more elements to the update clause .update({"status":"1", "colour":"red"}) or you can grab the object from the database and just change it as required:
item = db.session.query(Item).get(1) # grab the item with PK #1.
item.status = '1'
item.colour = 'red'
db.session.commit() # commit your changes to the database.

Categories