getting the Value of and HTML element - python

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.

Related

Failed to get value from html page in Django

I have a problem with trying to get a response from my HTML page using Django (admin).
I have a pretty simple div = contenteditable and need to pass data from this div back after the submit button was clicked.
Everything, including choosing selection and opening the intermediate page works fine. But when I tapped submit button, the condition if "apply" in request.POST failed to work.
Please, tell me, what I'm doing wrong?
This is my Django admin:
class QuestionAdmin(AnnotatesDisplayAdminMixin, admin.ModelAdmin):
def matched_skills(self, question):
return ', '.join(s.name for s in question.skills.all())
def update_skills(self, request, queryset):
if 'apply' in request.POST:
print("something")
skills = []
for question in queryset:
skills.append(self.matched_skills(question))
return render(request,
'admin/order_intermediate.html',
context={'skills': skills})
update_skills.short_description = "Update skills"
This is my order_intermediate.html page:
{% extends "admin/base_site.html" %}
{% block content %}
<form method="post">
{% csrf_token %}
<h1>Adjust skills. </h1>
{% for skill in skills %}
<div>
<div id="title" style="margin-left: 5px" contenteditable="true" > {{ skill }} </div>
</div>
{% endfor %}
<input type="hidden" name="action" value="update_status" />
<input type="submit" name="apply" value="Update skills"/>
</form>
{% endblock %}
Actually, request.POST is an HttpRequest object. For getting available keys in the body of the request, you need to use "request.POST.keys()" method. So, you can simply change your condition to:
if 'apply' in request.POST.keys():
print("something")
In my knowledge, you can not send div content with form submit. However you can use input tag with array in name attribute for this. This will send an array as post variable when submit
First, send skills as a enumerate object from your views
return render(request, 'admin/order_intermediate.html', context={'skills': enumerate(skills)})
Then edit your html to this (Note: if you have css in title id, change it to title class)
{% for i,skill in skills %}
<div>
<input class="title" name="skill[{{ i }}]" value="{{ skill }}" style="margin-left: 5px">
</div>
{% endfor %}
and handle array with any action you want to perform in update_skills()
for skill in request.POST.getlist('skill[]'):
# your code

Getting selected element of python list

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>

Form post to Django view renders no input to database

So, Im trying to save a todo to a database with django. My template is as follows:
<form action="{% url 'todo:add' %}" method="POST">
{% csrf_token %}
<input type="text" id="text" value="{{new_todo_text}}"/>
<input type="submit" value="Submit todo" />
</form>
{%if not_done_todos %}
<ul>
{%for todo in not_done_todos%}
<li>
<span>{{todo.text}}</span>
</li>
{%endfor%}
</ul>
{%else%}
<span>No todos for you!</span>
{%endif%}
My view where Im trying to catch the "new_todo_text" looks like this:
def add(request):
"""Add todo to database"""
new_todo = Todo(text=request.POST.get('new_todo_text'),
done=False, date_created=timezone.now())
new_todo.save()
return HttpResponseRedirect(reverse('todo:index'))
The problem is that the todo.text turns up empty no matter what I add to the form... whats my problem here?
The problem is that inside your input element you have not declared a name attribute. That name attibute will be used as a key to fetch it with Django request.POST.
So, change to this:
<input type="text" id="text" name="new_todo_text" value="{{new_todo_text}}"/>
The request.POST dict-like will use the input's name and value to build the dict. Then you can do stuff like request.POST['input_name_here'].

Not getting the Dropdown's data in Django view

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.

pagination is not working properly in django

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.

Categories

Resources