How to get the value of input on button click in django - python

I have a django template as follows
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Master Title</th>
<th>Retailer title</th>
<th>To add</th>
</tr>
</thead>
<tbody>
{% if d %}
{% for i in d %}
<tr>
<th scope="row">{{forloop.counter}}</th>
<td>{{i.col1}}</td>
<td>{{i.col2}}</td>
<td>
<input type="hidden" name='row_value' value="{{i.col1}}|{{i.col2}}">
<a class='btn btn-success' href="{% url 'match' %}">Match</a>
<a class='btn btn-outline-danger' href="{% url 'mismatch' %}">Not a Match</a>
</td>
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
When the match button is clicked, I want to retrieve the value of the hidden input in the views. Here is my views.py
def match(request):
print(request.GET.get('row_value'))
print('match')
But this returns None.
I want the values of col1 and col2 to be printed as follows
col1|col2
I am not sure where I am going wrong.

You should use Django URL params with GET:
urls.py
urlpatterns = [
path('your-path/<int:first_param>/<int:second_param>', views.match),
]
source: https://docs.djangoproject.com/en/3.2/topics/http/urls/#example
views.py
def match(request, first_param=None, second_param=None):
# then do whatever you want with your params
...
source: https://docs.djangoproject.com/en/3.2/topics/http/urls/#specifying-defaults-for-view-arguments
template:
<td>
<a class='btn btn-outline' href="your-path/{{i.col1}}/{{i.col2}}">Example</a>
</td>
This is a basic example, so change it to your use case.

Related

Flask redirect to url_for

I have he following data_analytics.html` which in the end provides the
view:
{% extends 'base.html' %} {% block title %}Home{% endblock %}
{% block content %}
<!-- <h1 align="center" >Your Files</h1> -->
<br />
<table class="table table-bordered table-hover">
<caption> Files Uploaded</caption>
<tr>
<th class="table-light"> # </th>
<th class="table-light">File Name</th>
<th class="table-light">Date</th>
<th class="table-light">Access Data</th>
</tr>
{% for file in csv_file %}
<tr>
<!-- <td>{{ file.id }}</td> -->
<th scope="row">1</th>
<td>{{ file.data }}</td>
<td>{{ file.date }}</td>
<td>View Data</td>
{%endfor%}
</table>
{% endblock %}
Is there a way that when the user clicks on the link to have displayed the content of the .csv file using python/flask ?
Tried to create a function that redirects to an url_for but not working`
try this:
In this 'a' put a 'target="_blank"'
View Data
And, in the python let's create a new function:
from flask import send_from_directory
#app.route('/csv')
def see_file():
return send_from_directory(directory='static', path='files/cheat_sheet.pdf')
Just change the path and the directory. And the file is going to open in a new tab.

remove from cart using form in template not working in Django

I'm building an Ecommerce App using Django, I'm storing my cart object in Django Sessions, Add to cart, reduce quanity & increase quantity seem to work perfectly on the products page but the same logic isnt working on the cart page. Django isnt throwing any errors. Below is the snippet of code of my form located inside a table on the Cart page & the view function handling its post request:
FORM:
<div class="container">
<div class="border rounded p-4 m-4">
<p class="display-4 pl-4 ml-4">Your Cart</p>
<hr>
<table class="table">
<thead>
<tr>
<th>Sno.</th>
<th>Image</th>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
<th> </th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td>{{forloop.counter}}</td>
<td>___</td>
<td>{{product.name}}</td>
<td>{{product.price}}</td>
<td>{{product|cart_quantity:request.session.cart}}</td>
<td>{{product|price_total:request.session.cart}}</td>
<td>
<form action="/cart/#{{product.id}}" method="POST">
{% csrf_token %}
<input hidden type="text" name="product" value="{{product.id}}">
<input hidden type="text" name="remove" value="True">
<input type="submit" value=" * " class="btn btn-block btn-light border-right">
</form>
</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<th colspan="4"></th>
<th class="" colspan="">Total</th>
<th>{{products|total_cart_price:request.session.cart}}</th>
</tr>
</tfoot>
</table>
VIEW FUNCTION:
class Cart(View):
def get(self, request):
ids = list(request.session.get('cart').keys())
products = Product.get_products_by_id(ids)
return render(request , 'cart.html' , {'products' : products} )
def post(self, request):
product = request.POST.get('product')
remove = request.POST.get('remove')
cart = request.session.get('cart')
if remove:
cart.pop(product)
else:
pass
return redirect('cart')
Apparently django sessions object needs to be made aware anytime any changes are to be made to the object inside sessions. The fix is to add :
request.session.modified = True
I'm testing this rn and it seems to work fine, what i dont get is why on the homepage it works without adding the modified command. If anyone has any further knowledge on this issue. Do share

The "Else if" statement in my Django templates appears after the HTML header block

I have some data which I am passing from my views to my templates, whenever the else if the statement is true(that is the if the statement is false) the statement appears after my HTML header().
My main issue is that why is the else block not under the HTML heaader where I have put it in the code
templates.html
<table class="table table-borderless table-data3">
<thead>
<tr>
<th>No</th>
<th>Email</th>
<th>Telephone</th>
<th>Country</th>
<th>Status</th>
<th>Image</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% if supplier %}
{% for supplier in suppliers %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{supplier.email}}</td>
<td>{{supplier.telephone}}</td>
<td>{{supplier.country}}</td>
<td class="process">Active</td>
<td>{{supplier.image.url}}</td>
<td>
<div class="table-data-feature">
<button class="item" data-toggle="tooltip" data-placement="top" title="Edit">
<i class="zmdi zmdi-edit"></i>
</button>
<button class="item" data-toggle="tooltip" data-placement="top" title="Delete">
<i class="zmdi zmdi-delete"></i>
</button>
</div>
</td>
</tr>
{% endfor %}
{% else %}
<h2>No supplier available</h2>
{% endif %}
</tbody>
</table>
You can not write a h2 in <tbody> or at least not directly. Yolu write this wrapped in a <tr> and <td>:
{% if suppliers %}
…
{% else %}
<tr><td colspan="7">No supplier available</td></tr>
{% endif %}
You also made a typo in the if statement: it is suppliers, not supplier.
Note: Django has a {% for … %}…{% empty %} template tag [Django-doc] that
can be used to render a message if the collection you iterate over is empty.
You can use the {% for … %}…{% empty %} django template tag. Example:
HTML
{% for supplier in suppliers %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{supplier.email}}</td>
<td>{{supplier.telephone}}</td>
<td>{{supplier.country}}</td>
<td class="process">Active</td>
<td>{{supplier.image.url}}</td>
<td>
<div class="table-data-feature">
<button class="item" data-toggle="tooltip" data-placement="top" title="Edit">
<i class="zmdi zmdi-edit"></i>
</button>
<button class="item" data-toggle="tooltip" data-placement="top" title="Delete">
<i class="zmdi zmdi-delete"></i>
</button>
</div>
</td>
</tr>
{% empty %}
<div><h2>No Suppliers Available</h2></div>
{% endfor %}

Create a custom URL and outputting HTML form data

For my first Flask project I wanted to create a basic Flask app using Riot Game's API for League of Legends. I've got all the processing of API working but I'm having trouble going about outputting it.
I take the input from a form on one page.
<form class="navbar-form navbar-left" action="{{ url_for('current_game_output') }}" method="POST">
<div class="form-group">
<input type="text" class="form-control" placeholder="Summoner Name" name="summoner_name">
<select class="form-control" name="region">
<option value="oce">Oceanic</option>
<option value="na">North America</option>
<option value="euw">Europe West</option>
</select>
</div>
<button type="submit" class="btn btn-default" value="Send">Submit</button>
</form>
And I am trying to output the data returned from the API onto the next page.
{% extends "header.html" %}
{% block body %}
<h3> Team 2 </h3>
<table class="table table-bordered" width="50%">
<tr>
<th width="48%">Summoner Name</th>
<th width="48%">Champion</th>
<th width="4%">Pic</th>
</tr>
{% for player in team1 %}
<tr>
<td>{{ player[0] }}</td>
<td>{{ player[1] }}</td>
<td><img width="20px" src="{{ url_for('static', filename='images/championIcons/') }}{{ player[1].replace(" ", "") }}_Square_0.png"></td>
</tr>
{% endfor %}
</table>
<h3> Team 1 </h3>
<table class="table table-bordered" width="50%">
<tr>
<th width="48%">Summoner Name</th>
<th width="48%">Champion</th>
<th width="4%">Pic</th>
</tr>
{% for player in team2 %}
<tr>
<td>{{ player[0] }}</td>
<td>{{ player[1] }}</td>
<td><img width="20px" src="{{ url_for('static', filename='images/championIcons/') }}{{ player[1].replace(" ", "") }}_Square_0.png"></td>
</tr>
{% endfor %}
</table>
{% endblock %}
I'd like the URL of the output page to be dynamic'/currentgame/region/username' but keep getting errors when trying to do so.
Relevant part of my views.py file (hidden my api key):
#app.route('/header')
def header():
return render_template("header.html")
#app.route('/current')
def current():
return render_template("current.html")
#app.route('/currentgame/<region>/<name>', methods=['POST'])
def current_game_output(region, name):
region = request.form['region']
summoner_name = request.form['summoner_name']
api = RiotAPI('APIKEYGOESHERE', region)
team1, team2 = current_game_data(summoner_name, region, api)
return render_template("output.html",team1=team1,team2=team2)
Any help/pointers on the best way to output/return the data would be appreciated.
Thanks
You should post the error as well.
In a quick looks this should be fixed:
#app.route('/currentgame/<string:region>/<string:name>', methods=['POST'])
def current_game_output(region, name):
region = request.form['region']
summoner_name = request.form['summoner_name']
api = RiotAPI('APIKEYGOESHERE', region)
team1, team2 = current_game_data(summoner_name, region, api)
return render_template("output.html",team1=team1,team2=team2)
Change route to /currentgame/<string:region>/<string:name>

Form fields not displayed in django html

I have written a code to make form , and i have no guess why the fields are not displayed here are my codes.
I want to get a request from the index.html page and using that request, I ran a query to display the results of the query on the same page.
views.py
def search123(request):
searc=search1()
if request.method=="POST":
searc=search1(request.POST or None)
if searc.is_valid():
if 'd_box' in request.POST:
item_map=item.objects.raw('SELECT * FROM `item` WHERE `category_id`=%s', [request.POST['d_box']])
lis=[]
for e in (item_map):
lis.append(e.id)
price_map=item_done.objects.filter(item_id__in=lis).order_by('item_id')
return render_to_response('index.html',{'posts':price_map},RequestContext(request))
return render_to_response('index.html',{'posts':searc},RequestContext(request))
index.html
<html>
<head>
</head>
<body>
<form method='POST' action=''>{% csrf_token %}
<h4> SEARCH </h4>
{{searc.as_table}}
<input type='submit' name="button7" value="button7">
</form>
{% regroup posts by item_id as post_list %}
<table border="4" style="width:1050px;border-collapse: collapse" >
<thead>
<tr>
<th>Item Codes</th>
<th>Name</th>
<th>MRP</th>
<th>Site price</th>
<th>Website</th>
</tr>
</thead>
<tbody>
{% for country in post_list %}
<tr>
<td>{{ country.grouper }}</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.name}}</div>
{% endfor %}
</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.mrp}}</div>
{% endfor %}
</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.site_price}}</div>
{% endfor %}
</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.crawl_id}}</div>
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</html>
forms.py
class search1(forms.ModelForm):
class Meta:
model=search
exclude=[]
i think you must import search model in forms.py an also in your template you write the form name wrong ! you write {{searc.as_table}} it must be {{search.as_table}}

Categories