Create a custom URL and outputting HTML form data - python

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>

Related

How to get the value of selected checkboxes from HTML into my Django Views?

Working for the first time on HTML and Djnago. I wrote a custom HTML
excluded_leagues.html
<h1>Excluded Leagues</h1>
<div class="excluded_leagues">
<form action="/superprofile/save_excluded_leagues/" method="POST">{% csrf_token %}
<table id="excluded_leagues_list">
<thread>
<tr>
<th scope="col">
<div class="text">
<span>Excluded</span>
</div>
</th>
<th scope="col">
<div class="text">
<span>League ID</span>
</div>
</th>
<th scope="col">
<div class="text">
<span>League Name</span>
</div>
</th>
<th scope="col">
<div class="text">
<span>Sport</span>
</div>
</th>
</tr>
</thread>
<tbody>
{% for league in object_list %}
{% if league.status == 'Active' %}
<tr>
<td><input type="checkbox" value="{{ league.id }}" name="selected_league"></td>
<td>{{ league.id }}</td>
<td>{{ league.name }}</td>
<td>{{ league.sport }}</td>
</tr>
{% else %}
{% endif %}
{% endfor %}
</tbody>
</table>
<div>
<button type="submit" name="apply">Save changes</button>
</div>
</div>
<ul>
I am trying to grab the league.id of all the selected checkboxes and use them in my views
views.py
def save_excluded_leagues(request):
if 'apply' in request.POST:
league_id_selected = request.POST.getlist('selected_league')
info_log.info(f"{league_id_selected } xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 1")
return HttpResponse("Hello")
I need to grab the values league.id of all the selected checkboxes, but I am unable to grab the value in my views.py file.
Right now it is not returning anything for the value request.POST.getlist('selected_league')
This is solved. I wrapped the checkbox part in
<td>
<div>
<input type="checkbox" value="{{ league.id }}" name="selected_league" {% if user_profile.is_free_money %} checked{% endif %}>
</div>
</td>
<td>{{ league.id }}</td>
<td>{{ league.name }}</td>
<td>{{ league.sport }}</td>

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

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.

Python Django Error during template rendering

let me quickly explain what am I trying to do.
So I am making a small Django based Conference Management, where there can be multiple conferences, a single conference can have multiple talks and each talk will have a certain number of Speakers and Participants.
I am able to list the conferences and give the option to delete and edit a conference.
Problem:
I want an option where I click on a conference and it shows a list of talks for that conference.
but when I click on the conference it shows the following error.
NoReverseMatch at /Big Data/talks/
Reverse for 'conferenceedit' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<id>[^/]+)/edit$']
Request Method: GET
Request URL: http://127.0.0.1:8000/Big%20Data/talks/
Django Version: 3.2.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'conferenceedit' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<id>[^/]+)/edit$']
Exception Location: E:\python\PYTHON and GIT\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix
Python Executable: E:\python\PYTHON and GIT\python.exe
Python Version: 3.9.1
Python Path:
['D:\\DjangoConferenceManagementSystem\\mysite',
'E:\\python\\PYTHON and GIT\\python39.zip',
'E:\\python\\PYTHON and GIT\\DLLs',
'E:\\python\\PYTHON and GIT\\lib',
'E:\\python\\PYTHON and GIT',
'C:\\Users\\AKS\\AppData\\Roaming\\Python\\Python39\\site-packages',
'E:\\python\\PYTHON and GIT\\lib\\site-packages',
'E:\\python\\PYTHON and GIT\\lib\\site-packages\\pip-21.0.1-py3.9.egg',
'E:\\python\\PYTHON and GIT\\lib\\site-packages\\win32',
'E:\\python\\PYTHON and GIT\\lib\\site-packages\\win32\\lib',
'E:\\python\\PYTHON and GIT\\lib\\site-packages\\Pythonwin']
Server time: Sun, 03 Oct 2021 15:47:10 +0000
I have included the following code to support the argument.
MODELS.PY
from django.db import models
from django.db.models.fields import CharField
from django.utils import timezone
# Create your models here.
class ConferenceModel(models.Model):
conference_title = models.TextField(null=False,primary_key=True)
conference_description = models.CharField(max_length=1000,null=False)
conference_start_date = models.DateField(null=False)
conference_end_date = models.DateField(null=False)
class TalkModel(models.Model):
talk_conference_title = models.ForeignKey(ConferenceModel,on_delete=models.CASCADE)
talk_title = models.TextField(null=False,primary_key=True)
talk_description = models.CharField(max_length=100,null=False)
talk_duration = models.DecimalField(max_digits=2,decimal_places=1)
talk_time = models.DateTimeField(null=False)
class SpeakerModal(models.Model):
speaker_talk_title = models.ForeignKey(TalkModel,on_delete=models.CASCADE)
speaker_username = models.CharField(max_length=25,null=False)
speaker_email = models.EmailField(max_length=100,primary_key=True,null=False)
class ParticipantModel(models.Model):
participant_talk_title = models.ForeignKey(TalkModel,on_delete=models.CASCADE)
participant_username = models.CharField(max_length=25,null=False)
participant_email = models.EmailField(max_length=100,primary_key=True,null=False)
URLS.PY
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('',views.conferenceView,name='conference'),
path('delete/<str:id>',views.conferencedelete,name='conferencedelete'),
path('<str:id>/edit',views.conferenceedit,name='conferenceedit'),
path('<str:id>/talks/',views.talkView,name='talks'),
path('admin/', admin.site.urls),
]
VIEWS.PY
from django.shortcuts import render
from django import forms
from django.shortcuts import render,HttpResponsePermanentRedirect,HttpResponse
from myapp.forms import ConferenceForm,TalkForm,SpeakerForm,ParticipantForm
from myapp.models import ConferenceModel,TalkModel,SpeakerModal,ParticipantModel
# Create your views here.
def conferenceView(request):
if request.method == 'POST':
conferenceform = ConferenceForm(request.POST)
if conferenceform.is_valid():
conferenceform.save()
conferenceform = ConferenceForm()
else:
conferenceform = ConferenceForm()
conference = ConferenceModel.objects.all()
return render(request,'myapp/conference.html',{'conference':conference,'conferenceform':conferenceform})
def conferenceedit(request,id):
if request.method == 'POST':
uniqueconferencetitle = ConferenceModel.objects.get(pk=id)
requestconferencedetails = ConferenceForm(request.POST,instance=uniqueconferencetitle)
if requestconferencedetails.is_valid():
requestconferencedetails.save()
return HttpResponsePermanentRedirect('/')
else:
uniqueconferencetitle = ConferenceModel.objects.get(pk=id)
requestconferencedetails = ConferenceForm(instance=uniqueconferencetitle)
return render(request,'myapp/conferenceedit.html',{'requestconferencedetails':requestconferencedetails})
def conferencedelete(request,id):
if request.method == 'POST':
conferencedelete = ConferenceModel.objects.get(pk=id)
conferencedelete.delete()
return HttpResponsePermanentRedirect('/')
def talkView(request,id):
talk = ConferenceModel.objects.get(pk=id)
conferencetalks = talk.talkmodel_set.all()
return render(request,'myapp/talks.html',{'conferencetalks':conferencetalks})
FORMS.PY
from django import forms
from django.db import models
from django.db.models import fields
from django.forms import widgets
from myapp.models import ConferenceModel,TalkModel,SpeakerModal,ParticipantModel
class ConferenceForm(forms.ModelForm):
class Meta:
model = ConferenceModel
fields = ['conference_title','conference_description','conference_start_date','conference_end_date']
widgets = {
'conference_title' : forms.TextInput(attrs={'class':'form-control '}),
'conference_description' : forms.TextInput(attrs={'class':'form-control'}),
'conference_start_date' : forms.TextInput(attrs={'class':'form-control','placeholder':'YYYY-MM-DD'}),
'conference_end_date' : forms.TextInput(attrs={'class':'form-control','placeholder':'YYYY-MM-DD'})
}
class TalkForm(forms.ModelForm):
class Meta:
model = TalkModel
fields = ['talk_conference_title','talk_title','talk_description','talk_duration','talk_time']
widgets = {
'talk_conference_title' : forms.HiddenInput,
'talk_title' : forms.TextInput(attrs={'class':'form-control '}),
'talk_description' : forms.TextInput(attrs={'class':'form-control '}),
'talk_duration' : forms.TextInput(attrs={'class':'form-control '}),
'talk_time' : forms.TextInput(attrs={'class':'form-control '}),
}
class SpeakerForm(forms.ModelForm):
class Meta:
model = SpeakerModal
fields = ['speaker_talk_title','speaker_username','speaker_email']
widgets = {
'speaker_talk_title' : forms.HiddenInput,
'speaker_username' : forms.TextInput(attrs={'class':'form-control '}),
'speaker_email' : forms.TextInput(attrs={'class':'form-control '})
}
class ParticipantForm(forms.ModelForm):
class Meta:
model = ParticipantModel
fields = ['participant_talk_title' , 'participant_username' , 'participant_email']
widgets = {
'participant_talk_title' : forms.HiddenInput,
'participant_username' : forms.TextInput(attrs={'class':'form-control '}),
'participant_email' : forms.TextInput(attrs={'class':'form-control '})
}
CONFERENCE.HTML
{% extends 'myapp/base.html' %}
{% block content %}
<div class="col-sm-5 container">
<h4 class="alert alert-info">Add a new conference</h4>
<form class="form-control" method="POST">
{% csrf_token %}
{{ conferenceform }}
<p></p>
<input type="submit" class="btn btn-success " value="ADD" id="add">
</form>
</div>
<div class="container mt-3">
<h4 class="alert alert-info text-center">
Here is the list of confrences
</h4>
<table class="table table-hover">
<th class="thead-dark">
<tr>
<th scope="col">Title</th>
<th scope="col">Description</th>
<th scope="col">Start Date</th>
<th scope="col">End Date</th>
<th scope="col">Options</th>
</tr>
</th>
{% for conferences in conference %}
<tr>
<th scope="col">{{conferences.conference_title}}</th>
<th scope="col">{{conferences.conference_description}}</th>
<th scope="col">{{conferences.conference_start_date}}</th>
<th scope="col">{{conferences.conference_end_date}}</th>
<td>
Edit
<form action="{% url 'conferencedelete' conferences.conference_title %}" method="POST" class="d-inline">
{% csrf_token %}
<input type="submit" value="Delete" class="btn btn-danger btn-sm">
</form>
</td>
</tr>
{% endfor %}
</table>
</div>
{% endblock content %}
TALKS.HTML
{% extends 'myapp/base.html' %}
{% block content %}
<div class="container mt-3">
<h4 class="alert alert-info text-center">
Here is the list of Talks under this conference
</h4>
<table class="table table-hover">
<th class="thead-dark">
<tr>
<th scope="col">Talk Title</th>
<th scope="col">Talk Description</th>
<th scope="col">Talk Duration </th>
<th scope="col">Talk Time</th>
<th scope="col">Options</th>
</tr>
</th>
{% for talkss in conferencetalks %}
<tr>
<th scope="col">{{talkss.talk_title}}</th>
<th scope="col">{{talkss.talk_description}}</th>
<th scope="col">{{talkss.talk_duration}}</th>
<th scope="col">{{talkss.talk_time}}</th>
<!-- <td>
Edit
<form action="{% url 'conferencedelete' conferences.conference_title %}" method="POST" class="d-inline">
{% csrf_token %}
<input type="submit" value="Delete" class="btn btn-danger btn-sm">
</form>
</td> -->
</tr>
{% endfor %}
</table>
</div>
{% endblock content %}
You loop through your queryset by naming the item conferences.
So to access the Id, since the URL expects an id. Look this path('<str:id>/edit',views.conferenceedit,name='conferenceedit'),.
You need to do this:
{% url 'conferenceedit' conferences.id %}
Or
{% url 'conferenceedit' conferences.pk %}
PS. Improve your path by updating '<str:id> to '<int:id>, since your model is integer.
urls.py
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('',views.conferenceView,name='conference'),
path('delete/<int:id>',views.conferencedelete,name='conferencedelete'),
path('<int:id>/edit',views.conferenceedit,name='conferenceedit'),
path('<int:id>/talks/',views.talkView,name='talks'),
path('admin/', admin.site.urls),
]
talks.html
{% extends 'myapp/base.html' %}
{% block content %}
<div class="container mt-3">
<h4 class="alert alert-info text-center">
Here is the list of Talks under this conference
</h4>
<table class="table table-hover">
<th class="thead-dark">
<tr>
<th scope="col">Talk Title</th>
<th scope="col">Talk Description</th>
<th scope="col">Talk Duration </th>
<th scope="col">Talk Time</th>
<th scope="col">Options</th>
</tr>
</th>
{% for talkss in conferencetalks %}
<tr>
<th scope="col">{{talkss.talk_title}}</th>
<th scope="col">{{talkss.talk_description}}</th>
<th scope="col">{{talkss.talk_duration}}</th>
<th scope="col">{{talkss.talk_time}}</th>
<!-- <td>
Edit
<form action="{% url 'conferencedelete' talkss.talk_conference_title_id %}" method="POST" class="d-inline">
{% csrf_token %}
<input type="submit" value="Delete" class="btn btn-danger btn-sm">
</form>
</td> -->
</tr>
{% endfor %}
</table>
</div>
{% endblock content %}
conference.html
{% extends 'myapp/base.html' %}
{% block content %}
<div class="col-sm-5 container">
<h4 class="alert alert-info">Add a new conference</h4>
<form class="form-control" method="POST">
{% csrf_token %}
{{ conferenceform }}
<p></p>
<input type="submit" class="btn btn-success " value="ADD" id="add">
</form>
</div>
<div class="container mt-3">
<h4 class="alert alert-info text-center">
Here is the list of confrences
</h4>
<table class="table table-hover">
<th class="thead-dark">
<tr>
<th scope="col">Title</th>
<th scope="col">Description</th>
<th scope="col">Start Date</th>
<th scope="col">End Date</th>
<th scope="col">Options</th>
</tr>
</th>
{% for conferences in conference %}
<tr>
<th scope="col">{{conferences.conference_title}}</th>
<th scope="col">{{conferences.conference_description}}</th>
<th scope="col">{{conferences.conference_start_date}}</th>
<th scope="col">{{conferences.conference_end_date}}</th>
<td>
Edit
<form action="{% url 'conferencedelete' conferences.pk %}" method="POST" class="d-inline">
{% csrf_token %}
<input type="submit" value="Delete" class="btn btn-danger btn-sm">
</form>
</td>
</tr>
{% endfor %}
</table>
</div>
{% endblock content %}
I got the problem was with my TALKS.HTML , I duplicated this HTML from the CONFERENCE.HTML and missed removing the following code.
<!-- <td>
Edit
<form action="{% url 'conferencedelete' conferences.conference_title %}" method="POST" class="d-inline">
{% csrf_token %}
<input type="submit" value="Delete" class="btn btn-danger btn-sm">
</form>
</td> -->
though I commented it , but it seems it wasn't commented , I removed it and now it works

Python, Django: get data from select-fields inside a table

inside my app I have a table that contains a select-field in each row. After pressing the submit-button I would like to receive all the selected values inside a list (or something else that's usable):
template:
<form method="POST">
{% csrf_token %}
<table name="table-example">
<thead>
...
</thead>
<tbody>
{% for item in list_example %}
<tr>
<td>...</td>
<td>...</td>
<td>
<select name="select-example">
{% for item in list_selections %}
<option name="option-example" value="{{ item }}">{{ item }}</option>
{% endfor %}
</select>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<button type="submit">Update</button>
</form>
When trying to receive data from I only get one field!
if request.method == "POST":
data = request.POST.get('option-example', None)
What am I doing wrong or what am I missing here? Or is this even possible?
Thanks for all your help and have a great day!

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