Using Django templates to set default values - python

So, I'm making a search function and I would like the previously entered query to remain in the search box when the search results are rendered. Currently the way that I'm doing this is by sending a POST request, grabbing the query and sending that back to the template as a variable. For some reason though, it will only work for the first word of the query, and all subsequent words get dropped. When I render the same variable within a tag however it comes out just as I would expect. Is there something there I'm not doing quite right?
<div id="searchwrapper">
<form action="/search" method="post"> {% csrf_token %}
{% if old_query %}
<input type="text" class="searchbox" name="s" value={{old_query}} />
{% else %}
<input type="text" class="searchbox" name="s" value="" />
{% endif %}
<input type="image" src="static/images/search-icon.svg" class="searchbox_submit" value="" />
</form>
</div>
def search(request):
context = {}
context.update((csrf(request)))
results_string = ""
if request.POST:
results_string = find(request)
old_query = request.POST['s']
context.update({"old_query": old_query})
search_bar = render_to_string("search.html", Context(context))
return HttpResponse(search_bar + results_string)
I don't think that the find method is relevant, but let me know if you think it would be useful and I can post it. The template is the relevant part of "search.html" Like I said, if I add the line <p>{{ old_query }}</p> to the {% if old_query %} section, the right value shows up, but at present if I used a query like hello stackoverflow! I would only get "hello" in as the value for the search field.
This is probably something silly, but I'm fairly new to web dev, so any help is appreciated.

Fix this line to wrap {{old_query}} between quotes:
<input type="text" class="searchbox" name="s" value="{{old_query}}" />
That should give you the whole search instead of the first word.

Related

How can I generate buttons or fields (forms) in Flask according to a list of strings?

Well, suppose we have a list of strings (objects with a toString() method respectively) and a jinja2 template that shall have selection forms (buttons or something alike) that agree in number and label to the list. This list may alter during the session. So far, I tried to work with submit buttons and radio buttons. Problems are: submit buttons vary in size because of different string length and I dislike that radio buttons force the user to first make a choice and then submit it.
The jinja2 markup looks like this:
<form method = 'post' action= "{{ url_for('add_dialogue_turn') }}">
{% if questions %}
{% for q in questions %}
<input type="radio" name="question" value={{q}}> {{q}} <br>
{% endfor %}
{% endif %}
<input type="submit" /><br /><br />
</form>
The flask function looks like this:
#app.route("/turn", methods=['POST'])
def add_dialogue_turn():
label = request.form["question"]
print(label)
return render_template("sometemplate.html", questions=aListOfQuestions, answers = aListOfAnswers)
Can I make the radio buttons submit the value directly after ticking off the circle? Or can I define some field that returns the string when clicking on it?
Thank you for your help in advance!
This is a Front end problem. You would need either JavaScript to submit your form when a button/radio is ticked. And it also depends on how you submit your form but if you want just the data to be passed into the server without page reloading, I'd suggest Ajax. And if you just want to pass the input value into the server, you do not have to use post.
A simple example would be,
-HTML
<input type="radio" name="question" value={{q}} id="{{something_unique_for_each_iterable}}" onclick="submitFunction(this)">
-JavaScript
function submitFunction(event){
id_of_radio_ticked = '#' + event.id;
$.ajax({
url: "{{url_for('to_your_flask_view_function')}}",
type: 'GET',
data: {'radio_value':$(id_of_radio_ticked).val()},
success: function(resp){
alert('do something with returned data')
}
});
}
I found another solution within the jinja template:
<nav>
<ul>
<div class="sideMenuL">
<form method = 'post' action= "{{ url_for('add_dialogue_turn') }}">
{% if questions %}
{% for q in questions %}
{% autoescape false %}
<input type="submit" name="question" value="{{q}}"><br>
{% endautoescape %}
{% endfor %}
{% endif %}
</form>
</div>
</ul>
</nav>

Search function in Flask

I have a problem with my search. At the moment i am trying to write a small receipe portal and i am trying to search words in tables user,category and recipe. When i write some word, i receive an error message:
Bad request. The browser (or proxy) sent a request that this server
could not understand.
I suppose, that problem stays in my function search, but i dont see it.
#app.route("/search", methods=['GET', 'POST'])
def search():
cursor = g.con.cursor()
cursor.execute('SELECT * FROM nutzer, kategorien, rezepte WHERE Nutzername OR Titel = %s', (request.form["search"],))
result = cursor.fetchall()
cursor.close()
return render_template('Results.html', result = result)
{% extends "layout.html" %}
{% block body %}
<table border="1">
{% for i in result %}
<tr><td>{{ i.1 }}</td></tr>
{% endfor %}
</table>
{% endblock %}
HTML Code of the searchbar
<form action="search">
<input name="search" type="text" placeholder="suchen" value="{{ request.form.search}}" required />
<button>finden</button>
</form>
request.form() implies the POST method, while the default one is GET. You should either check request.method and use request.args() in the case of GET, or add the argument method="POST" to the <form> (and leave POST as the only accepted method in #app.route().
I think your form action has to point to your search endpoint.
<form action="{{ url_for(search) }}">
<input name="search" type="text" placeholder="suchen" value="" required />
<button>finden</button>
</form>

In Django, how do I access template values in the views.py?

I'm fairly new to Django and I'm working on a page that takes in user information. If all of the information is correct, it will proceed to the next page. However, if the user does not provide all given info, it will to refresh the page. My problem is that there are quite a bit of fields the user has to fill out and if the person misses any fields, I don't want them to have to re-type everything out. So my workaround for it is that in the views.py I created a dictionary and it populates it with the input names in the template. However, when I go to run the code, it gives me an error saying that the values in my dictionary do not exist. I'm now thinking that my dictionary is not actually accessing any of the template values.
Here is my template:
<!DOCTYPE html>
{% extends "Checklist/base.html" %}
{% block main_content %}
{% load static %}
<html>
<body>
<form action="{% url 'Checklist:signin_check' %}" method="post">
{% csrf_token %}
<ul style="list-style-type:none">
<li>
<label for="driver_first_name">Driver First Name:</label>
<input type="text" name="driver_first_name" value="" id="driver_first_name">
</li>
<li>
<label for="driver_last_name">Driver Last Name:</label>
<input type="text" name="driver_last_name" value="" id="driver_last_name">
</li>
<li>
<label for="driver_wwid">Driver WWID:</label>
<input type="text" name="driver_WWID" value="" id="driver_WWID" maxlength="8"
onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57">
</li>
<li>
<label for="co_driver_first_name">CO-Driver First Name:</label>
<input type="text" name="co_driver_first_name" value="" id="co_driver_first_name">
</li>
<li>
<label for="co_driver_last_name">CO-Driver Last Name:</label>
<input type="text" name="co_driver_last_name" value="" id="co_driver_last_name">
</li>
<li>
<label for="co_driver_wwid">CO-Driver WWID:</label>
<input type="text" name="co_driver_WWID" value="" id="co_driver_WWID" maxlength="8"
onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57">
</li>
<li>
<input type="submit" value="Continue">
</li>
</ul>
</form>
</body>
</html>
{% endblock %}
Here is the views.py:
def signin_check(request):
driver_info_model = Driver()
if request.method == "POST":
driver_info_form = Driver_Form(request.POST)
c = {'driver_first_name':driver_first_name, 'driver_last_name':driver_last_name,
'driver_WWID':driver_WWID, 'co_driver_first_name':co_driver_first_name,
'co_driver_last_name':co_driver_last_name, 'co_driver_WWID': co_driver_WWID,}
if driver_info_form.is_valid():
driver_info_form.save()
return render(request, 'Checklist/checklist.html')
template = loader.get_template('Checklist/signin.html')
return HttpResponse(template.render(c, request))
any feedback would be greatly appreciated. Thanks!
However, when I go to run the code, it gives me an error saying that
the values in my dictionary do not exist. I'm now thinking that my
dictionary is not actually accessing any of the template values.
From your views.py alone I'm guessing the exception you're running into is that you're assigning dictionary values that aren't defined. For example, in 'driver_first_name':driver_first_name, Python is looking for a variable named driver_first_name but you haven't defined it. The data you're looking for, as Justin alluded to, can be found in requests.POST.
One solution, while more verbose, illustrates what needs to be done:
def signin_check(request):
driver_info_model = Driver()
if request.method == "POST":
driver_info_form = Driver_Form(request.POST)
driver_first_name = request.POST.get('driver_first_name', '')
driver_last_name = request.POST.get('driver_last_name', '')
driver_WWID = request.POST.get('driver_WWID', '')
co_driver_first_name = request.POST.get('co_driver_first_name', '')
co_driver_last_name = request.POST.get('co_driver_last_name', '')
co_driver_WWID = request.POST.get('co_driver_WWID', '')
c = {'driver_first_name': driver_first_name,
'driver_last_name': driver_last_name,
'driver_WWID': driver_WWID,
'co_driver_first_name': co_driver_first_name,
'co_driver_last_name': co_driver_last_name,
'co_driver_WWID': co_driver_WWID, }
if driver_info_form.is_valid():
driver_info_form.save()
return render(request, 'Checklist/checklist.html')
template = loader.get_template('Checklist/signin.html')
return HttpResponse(template.render(c, request))
My problem is that there are quite a bit of fields the user has to
fill out and if the person misses any fields, I don't want them to
have to re-type everything out.
To address your second concern you'll need to deal with your HTML template. Your input fields have a value of "", so any value you pass through your context is not going to reach any of them. Luckily you're on the right path and you're quite close, so all you need to do is fill those values in. For example:
<li>
<label for="driver_first_name">Driver First Name:</label>
<input type="text" name="driver_first_name" value="{{ driver_first_name }}" id="driver_first_name">
</li>
Note that {{ driver_first_name }} is referencing the driver_first_name that's being passed into the context.
Im not 100% sure as i'm fairly new to Django myself, but from what i've done previously you can get the POST data from the request that is passed in, like this:
request.POST['driver_first_name']
which raises an error if no data is present or from
request.POST.get('driver_first_name', 'optionaldefaultvalue')
which returns None if no data is present in the specified field, or an optional default.
It might also be easier to do what you are after with django's inbuilt forms

Display form input with Django

So basically I want to make a simple form I can enter text and the after I hit submit, see the text.
Here is my forms.py:
class Search(forms.Form):
search = forms.CharField()
Here is my views.py:
def search(request):
context = RequestContext(request)
if request.method == 'POST':
search = Search(data=request.POST)
if search.is_valid():
ticker = search.save()
ticker.save()
success = True
else:
print search.errors
else:
search = Search()
return render_to_response('ui/search.html', {"search":search}, context)
Here is the html form that you use to type in (I'm using bootstrap for styling purposes):
<form class="navbar-form navbar-right" role="search" action="/search/" method="post" name="tick">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter stock symbol">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
And finally, I want the text entered in the form to be displayed on "search.html" which looks like this currently:
{% extends 'ui/base.html' %}
{% block title %} search {% endblock %}
{% block body_block %}
<br>
<p>test</p>
{{ form.search.data }} <!--I'm pretty sure this is not correct -->
{% endblock %}
Anyone know how I can do this? Thanks.
Your form name is search.
To render the value with modern django, you need to call the value method of the field, therefore your template should look like the following:
{{ search.search.value }}
Your template is wrong, as you suspect.
It is looking for a context variable named "form", but you have given it a context dictionary with a key named "search".
Also, "data" is the argument that you use to build up your Search object (correctly), but when you want to extract the user's input from it, you should use the field names instead, and you need to call value() on them in order to get the bound value. So, to get the contents of the text field called search, you should use search.search.value.
Try changing the line
{{ form.search.data }}
to
{{ search.search.value }}

How can you manually render a form field with its initial value set?

I'm trying to render a form's fields manually so that my designer colleagues could manipulate the input elements within the HTML instead of struggling in Python source.
ie. Instead of declaring form fields like this...
{{ form.first_name }}
.. I actually do ...
<label for="id_first_name">Your name:</label>
<input type="text" value="{{ form.first_name.somehow_get_initial_value_here }}" name="first_name" id="id_first_name" class="blabla" maxlength="30" >
{% if form.first_name.errors %}<span>*** {{ form.first_name.errors|join:", " }}</span>{% endif %}
Problem is that there seems to be no way to get the initial value of the field in the second method. {{ form.first_name }} statement does render the input element with the proper initial value but somehow there is nothing like {{ form.first_name.initial_value }} field when you want to render the form manually.
There is an interesting long standing ticket about this very issue. There is sample code to implement a template filter in the comments that should do what you need:
http://code.djangoproject.com/ticket/10427
<input value="{{form.name.data|default_if_none:'my_defaut_value'}}" ... />
You will have to use default_if_none because the implicit value of a bound field will not be stored in data. More details here

Categories