I have a list of 6 elements. I get it as a dropdown through bootstrap-select. I can receive element of list in the console only if the form is submitted for handling.
Main question is:
How to make it so that when I select an element, I can immediately get it(print it) in the console, before submitting the form?
app.py
description = ['one','two','three','four','five','six']
#app.route('/', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
docs = request.form.getlist('sel')
print(docs)
return render_template('login.html', description=description)
return render_template('login.html', description=description)
login.html
<form action="" method="POST" class="form-inline">
<select id='sel' name='sel' class="selectpicker" multiple data-live-search="true">
{% for desc in description %}
<option value="{{desc}}">{{desc}}</option>
{% endfor %}
</select>
<button type="submit" class="btn btn-primary">Identify</button>
</form>
<script type="text/javascript">
$('select').selectpicker();
</script>
If you want to print in the console, you don't need to work on the app.py, however, you need to work on your login.html.
To enable this, your answer is onchange, which is predefined for the <select>, captures your data when you select an option. No need to have a submit button either.
UPDATED ANSWER: The <p> waits for the value, which is being set inside our function printValue()
<select id='sel' name='sel' class="selectpicker" multiple data-live-search="true" onchange="printValue(this)">
{% for desc in description %}
<option value="{{desc}}">{{desc}}</option>
{% endfor %}
</select>
<p id="mySelectedValue" style="margin-top: 10px;"></p>
<!-- In your script, call your function, which prints the data in your console-->
<script type="text/javascript">
function printValue(selectedItem){
$('#mySelectedValue').html(selectedItem.value);
}
</script>
In the method printValue(), you print your data value using the method :). You can do anything, here, like adding to selected item to your array or Map. It is upto, we're just printing in console for the sake of requirement :)
This is the SNIPPET for the REFERENCE on how onchange works in SELECT.
function printValue(selectedItem){
console.log(selectedItem.value);
}
<select class="form-control" id="your_id" onchange="printValue(this)">
<option value="Value1" selected>Value1</option>
<option value="Value2">Value2</option>
<option value="Value3">Value3</option>
</select>
Related
As you can see in the picture below I'm trying to have the user search for a given country, start/end date and get the result of "Confirmed Cases" and "Date" back from the API, but I'm not sure how to do it.
I tried using this API, to fill the drop-down menu of the countries -->
https://api.covid19api.com/summary
but this is the other API that I have to use but while changing the parameters for the country and dates -->
https://api.covid19api.com/country/afghanistan/status/confirmed?from=2020-09-06T00:00:00Z&to=2020-09-11T00:00:00Z
Here are snippets of my code:
views.py
def home(request):
# second_response = requests.get('https://api.covid19api.com/country/afghanistan/status/confirmed?from=2020-09-06T00:00:00Z&to=2020-09-11T00:00:00Z').json()
second_response = requests.get('https://api.covid19api.com/summary').json()
my_list = []
for i in range(0, len(second_response['Countries'])):
my_list.append(second_response['Countries'][i]['Country'])
if request.method=='POST':
selected_country = request.POST['selected_country']
print('here', selected_country)
return render(request, 'home.html', {'my_list': my_list})
home.html
<div class="container justify-content-center">
<form action="{% url 'home' %}" method="post">
{% csrf_token %}
<label for="selected_country" style="margin-right: 5px;"> Select a Country, Start & End Dates : </label>
<select name="selected_country" >
{% for object in my_list %}
<option value="">{{object}}</option>
{% endfor %}
</select>
<label for="startdate"></label>
<input type="date" id="startdate">
<label for="enddate"></label>
<input type="date" id="enddate">
<input type="submit" value="Search" />
</form>
</div>
PLUS: when I click on "search" i should get the value of the selected_country because I tried printing it, but it doesn't show for some reason, so the method is post but for some reason I can't get back the selected_country
Any help is appreciated
JAVASCRIPT
if you have any solid grasp of javascript i recommend you do that in javascript, because it will just make it better and easier
otherwise :
view.py
def handler(request):
if request.method=='POST':
selected_country = request.POST['selected_country']
startDate= request.POST['startdate']
endDate= request.POST['enddate']
request_handler = requests.get(f"https://api.covid19api.com/country/{selected_country}/status/confirmed?from={startDate}T00:00:00Z&to={endDate}T00:00:00Z")
if request_handler.status_code=200:
#To prevent errors
request_json=request_handler.json()
else:
pass # do something
return render(request, 'result.html', {"json":request_json})
#you should handle the data at the front end using jinja blocks
note : i don't know much about Django so the code may break
I want to send a basic form to views. I create everything that it need but when I submit the post, it doesn't send a return a blank page.
This is my form and app:reports is the same page with form, because I want to return the same page. I need the values of year_one and year_two.
<form method="post" action="{% url 'app:reports' %}">
{% csrf_token %}
<label for="year_one">Select year 1:</label>
<select id="year_one" name="year_one">
{% for case in query_trend %}
<option value="{{case.date_created__year}}" >{{case.date_created__year}}</option>
{% endfor %}
</select>
<label for="year_two">Select year 2:</label>
<select id="year_two" name="year_two">
{% for case in query_trend %}
<option value="{{case.date_created__year}}">{{case.date_created__year}}</option>
{% endfor %}
</select>
<button onclick="test()">click</button>
</form>
And this is my view
if self.request.method == 'POST':
year_one = self.request.GET.get('year_one')
year_two = self.request.GET.get('year_two')
return HttpResponseRedirect('fdm:outstanding_reports')
What should I do for using these values in views?
Assuming your button's test() method is successfully submitting the form...If you are passing the request to your view,ie,
def reports(request):
Then you can refer to the posted values of year_one and year_two as:
if request.method == 'POST':
year_one = request.POST.get('year_one')
year_two = request.POST.get('year_two')
(GET is when you send values contained in the URL, eg page?year_1=1975&year_2=1300, POST is when it happens in the background. A form will generally use only one or the other, so you your version probably wasn't getting any values. Confusingly, you also use the lowercase '.get()' to retrieve the POST values)
I am designing a web app for my final project in CS50. I need to connect two users as friends(like FB). In order to connect the users in my database I need to get the Value of a generated HTML element.
I am using flask
I tried to get the Value of the element with:
request.form.get('value')
request.args.get('value')
both return none
<div>
<ol>
{% for x in range(rows|length) %}
<form value='{{loop.index}}' action="connect_friends" method="POST">
<li name="friend" value='{{loop.index}}'> <a>{{rows[loop.index -1][1]}} {{rows[loop.index -1][2]}}</a> add to
<select name='groups'>
{% for x in range(5) %}
<option value='group {{loop.index}}'>Group {{loop.index}}</option>
{% endfor %}
</select>
<button class="btn btn-primary" type='submit'>Add</button>
<br>
<br>
</form>
{% endfor %}
</ol>
#app.route("/connect_friends", methods=["POST"])
def connect_friends():
if request.method == "POST":
# getting the group number-- this works as expected
group_number = request.form.get('groups')
# getting the value of the HTML element this returns NONE
friend = request.form.get('friend')
# printing to check
print(group_number)
print(friend)
return apology(f"{group_number}")
else:
return apology("something went wrong", 403)
the expected output is that
friend is not NONE
It's because you're using an li tag which will not be passed in with the request.
You can try this:
<input style="display:none;" name="friend" value="{{loop.index}}" />
Put that input somewhere within your <form> ... </form> area and you should get the value.
I was trying to get the item selected in the Dropdown menu of the form. But i can't access the selected item. So to check, whether the data is available in views.py i used messages.error().But it shows None like
Here is the form:
<form method="post" name="deleteitemform" id="deleteitemform" style="padding-bottom:50px; padding-top:10px;">
{% csrf_token %}
<div class="input-group">
<span class="input-group-addon" id='prepandID'>Item Name :</span>
<select class="form-control" id="delete-item-select" name='delete_select'>
{% for item in items %}
<option value="{{item.item_name}}">{{item.item_name}}</option>
{% endfor %}
</select>
</div>
<button class="btn btn-primary col col-md-2 col-md-offset-5" style="margin-top:10px;" name='deletebutton' type="submit">Delete</button>
</form>
And in views.py:
if 'deletebutton' in request.POST:
selected_item = request.POST.get("detele_select", None)
# to_be_deleted = Item.objects.filter(item_name=selected_item)
# to_be_deleted.delete()
messages.error(request, str(selected_item))
return redirect('/restaurant/updateitems')
else:
return redirect("/")
I am not sure what I am doing wrong. Can anyone help on this regard?
In views you use detele_select instead of delete_select specified in your form.
By the way, it is easier and more convenient to use Django forms. It does a lot of work instead of you.
I have a code that submit the form according to the date. Whenever I use pagination on the formit displays an error
"Key 'userchoice' not found in <QueryDict: {}>"
Pagination limits data to display properly, but when I click "next" it displays an error.
Here's what I've got so far:
views.py :-
def testeruser(request):
getchoice = request.POST['userchoice']
getfirstdate = request.POST['firstdate']
getseconddate = request.POST['seconddate']
# getfirstdate = '2013-09-25'
# getseconddate = '2013-09-26'
if getchoice == '0':
getdata = applicationform.objects.filter(date__gte=getfirstdate , date__lte=getseconddate)
##### PAGINATION
searchpagination = Paginator(getdata ,3)
page=request.GET.get('searchpage')
try:
searchcontacts = searchpagination.page(page)
except PageNotAnInteger:
searchcontacts = searchpagination.page(1)
except EmptyPage:
searchcontacts = searchpagination.page(searchpagination.num_pages)
if getdata:
return render_to_response('registration/search_page.html', {'getdata':getdata ,'getchoice':getchoice ,'searchcontacts': searchcontacts})
else:
return HttpResponse('NO ITEMS FOUND ON THIS DATE')
in custom templates :-
<form method="POST" action="/testeruser/" class="form-horizontal" name="searchform" enctype="multipart/form-data" >{% csrf_token %}
<select name="userchoice" id="client_specification" class="span2" required> <option value='-1'>Select Your Choice </option>
<option value='0'>Biddings</option>
<option value='1'>Interviews</option>
<option value='2'>Jobs</option>
</select>
From: <input type="text" class="input-xlarge" name="firstdate" id="search1" readonly="readonly" />
To: <input type="text" class="input-xlarge" name="seconddate" id="search2" readonly="readonly"/> </span>
<button class="btn btn-gebo" type="submit" name="asubmit" >Submit</button>
</form>
<!------------ PAGINATION---------------->
<div class="pagination">
<ul> {% if searchcontacts.has_previous %}
<li>PREVIOUS</li>
{% endif %}
{% if searchcontacts.has_next %}
<li>NEXT</li>
{% endif %}
</ul>
</div>
<!------------ PAGINATION---------------->
Pagination in Django works fine, it's your code that's the problem.
For some reason, you're using POST to send the original search variables, but then creating pagination links that just do GET with a page number. Of course, Django has no way of knowing what your previous search criteria are, since you're not sending them in the POST data - hence the error.
The normal way to do this is to send the original search request via GET - that is best practice anyway, since a search does not modify data. Then you include those same variables on all the pagination links, simply replacing the page number.