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.
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 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 have a jinja2 template with a simple user preferences form. The preferences are passed as a python dictionary into the render_template() function. Depending on a setting, I need to mark one of the radio buttons in a group as checked.
Q: How to do it cleanly, without much code repetition?
Below is my current solution. It works, but it's ugly, and with more than 2 radio buttons, it would soon become hard to manage. There is probably a better way.
I use two string variables (for the 2 radio btns). One of them will be empty, and the other will be set to 'checked', according to the preference setting:
{% if user_prefs['when_done'] == 'index' %}
{% set indexchecked = 'checked' %}
{% set backchecked = '' %}
{% else %}
{% set indexchecked = '' %}
{% set backchecked = 'checked' %}
{% endif %}
<!-- With more radio buttons here, this would be a mess! -->
And then I use these strings in the template:
<form action="{{ url_for('prefs') }}" method="post">
<fieldset>
<div class="radio text-left">
<p><strong>After completing a task:</strong></p>
<label>
<input type="radio" name="when_done" value="index" {{ indexchecked }}>
Return to homepage
</label>
<br/>
<label>
<input type="radio" name="when_done" value="task" {{ taskchecked }}>
Go to next task
</label>
</div>
<div class="form-group">
<button class="btn btn-default" type="submit">Update preferences</button>
</div>
</fieldset>
</form>
I would move the computation of indexchecked and backchecked from the template to the code. You can also use dictionary unpacking in order to pass less parameters to the render_template method.
do_index = user_prefs['when_done'] == 'index'
index_checked = 'checked' if do_index else ''
back_checked = '' if do_index else 'checked'
render_template('pages/something.html', form=some_form, index_checked=index_checked, back_checked=back_checked)
In order to reduce the number of passed parameters you can use a dict with unpacking:
template_parameters = dict(form=some_form, index_checked=index_checked, back_checked=back_checked)
render_template('pages/something.html', **template_parameters)
First of all sorry if that's a silly question, but I am kind of stuck..
I want to pass a couple of variables from my HTML/Bootstrap page to Flask. The variables are obtained in a form.
The variable is to be selected from a dropdown. Once the variable is selected from mySQL2 it should be stored in customername.
At the moment I've got this sample code which does not work at all.
<form action="" class="form-group" method="post">
<div class="form-group">
<label for="selectcustomer">Select your customer</label>
<input
<select class="form-control" id="selectcustomer">
{% for j in mySQL2 %}
<option>{{j[2]}}</option>
{% endfor %}
</select> value="{{request.form.customername}}">
<input type="text" class="form-control" name="customername" value="{{request.form.customername}}">
</div>
<br>
<input class="btn btn-default" type="submit" value="Submit">
</form>
How can I post the selected value into customername?
The form looks like this:
I need the selection field to be a dropdown. Once a value is selected it should be stored in customername.
Before form submission can't get the submit values. To get posted data in view use:
request.form["selectcustomer"]
note: html select tag should have a name attribute <select name="selectcustomer" ...> so you can get value with name not the select id.
Lets say you have a view as follows:
def customer():
customername = ""
if request.method == 'POST':
customername = request.form["customername"]
return render_template("yourhtmlfile", customername=customername)
#yourhtml
...
{{customername}}
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.