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'].
Related
This is my html form in which i have a text field for a word and i am running a for loop which created checkbox for the list of document a user has and displays it as form.
<body>
<form id="form" method = "POST">
{% csrf_token %}
<fieldset id="User">
<legend>Your details:</legend>
<p><label for="word">Enter your word</label>
<input type="text" id="word" name="word">
</p>
{% for doc in docs %}
<p>
<input type="checkbox" id="{{ doc.document_id }}" name="docid" value="{{ doc.path }}">
<label for="{{ doc.document_id }}"> {{ doc.document_name }} </label><br>
</p>
{% endfor%}
<input type="submit" value="Submit" >
</fieldset>
</form>
</body>
In views.py I have below method which loads this html page
def client_home(request):
client_pr = Client_Profile.objects.get(user_id=request.user)
events = Event.objects.filter(client_id=client_pr.pk)
name = request.POST.get('word')
id = request.POST.get('docid')
print(name)
print(id)
docs = []
for eve in events:
docs = Document.objects.filter(event_id=eve)
context = {'events': events, 'docs': docs}
return render(request, 'Elasticsearch/form.html', context)
My question is as i am using a for loop create checkbox field based on number of documents a user has and when I try to print them in my Views.py file it is only priniting last document id whose checkbox is created and not all the documents.
From seeing your view, I assume you want to pass a list of documents specific to a user to your template. Currently you are overwriting docs in every iteration of your for loop.
Change
docs = Document.objects.filter(event_id=eve)
to
docs += Document.objects.filter(event_id=eve)
You need to use getlist to get all the selected values from your checkbox, so:
id_list = request.POST.getlist('docid')
Otherwise using get will only return the last one.
I am trying to develop some basic django templates where i initially pass the django template variable which is an array - {{array_list}}. I am able to perform operations on this dtv easily. But I am unable to post this variable back to views.
Eg. I pass {'array_list': [1,2,3,4]}
<form action="some_action" method="post">
{% csrf_token %}
<input type="submit" value="sort">
<input type="hidden" name="array_list" value={{array_list}}>
</form>
And in views.py:
array_list = request.POST['array_list']
return render(request, 'result.html', {'array_list': array_list})
But i don't get the full array back to result.html, and i only get [1, as the array_list.
Probably you can do something like this:
First, use join tag to turn that list into comma separated string.
<form action="some_action" method="post">
{% csrf_token %}
<input type="submit" value="sort">
<input type="hidden" name="array_list" value='{{array_list|join:","}}'>
</form>
And get the value in POST request and split it by ,.
array_list = request.POST['array_list'].split(',')
I have an HTML page with a series of list items. I would like to be able to push a button, read the data in the list, and do a sort of transformation. I thought it would be rather like this example.
However, this format uses the name attribute to get the data and neither a list or list item can have names!
My HTML:
<form action="{% url 'index' %}" method="POST">
{% csrf_token %}
<ul id="myList">
<li id="myId1">First Item</li>
<li id="myId2">Second Item</li>
</ul>
<button type="submit">Submit</button>
</form>
My python:
def index(request):
if request.method == 'POST':
var = request.POST['myList']
print(var)
return render(request, "test.html", {})
Is there a way to get items in a list?
Additional Information:
Current output is just None.
I can grab data like text boxes just fine, those are named items.
I have tried a few other suggestions, like var = request.POST.get('myList'), and even started dealing with forms and
models but I could only grab data that was IN the model that way, not a <li>.
You have to have input tags with name attributes inside your form for it to submit any data to the server. Just sticking some list items in there will do nothing - HTML forms require inputs.
Something like this might work for you:
<form action="{% url 'index' %}" method="POST">
{% csrf_token %}
<ul id="myList">
<li id="myId1">First Item <input type="hidden" name="mylist[]" value="myid1"></li>
<li id="myId2">Second Item <input type="hidden" name="mylist[]" value="myid2"></li>
</ul>
<button type="submit">Submit</button>
</form>
i.e, insert a hidden input into each item in your list, with name and value attributes, that should then result in something being available in request.POST.getlist('mylist').
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 currently have a working search form in my project that passes through form data to the GET request. Pretty standard.
What I'm wanting to do is search as data is entered into the search form, so that results will display in real time with search data. This is much like what Google does with the instant desktop results. Is this something that's possible with Django?
Below is my current (simple) search
#views.py
def ProductView(request):
title = 'Products'
all_products = Product.objects.all().order_by("product_Name")
query = request.GET.get("q")
if query:
products = all_products.filter(
Q(product_Name__contains=query) |
Q(manufacturer__contains=query)
).distinct()
return render(request, 'mycollection/details.html', { 'all_products' : products })
-
<!-- HTML -->
<!-- SEARCH BAR -->
<form class="navbar-form navbar-left" role="search" method="get" action="{% url 'mycollection:products' %}">
<div class="form-group">
<input type="text" class="form-control" name="q" value="{{ request.GET.q }}">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
you can save the request.data in to session and if any data is associated with session search data you can put in to value of search box.
request.session['search'] = request.GET.get('q','')
templete :
{% if request.session.search %} {{request.session.search}} {% endif %}