I have a list of zones, identified by id (integer).
How can I get the zone that generated the post request?
manual.html
{% if zone_list %}
<ul>
{% for z in zone_list %}
<b><p>{{z.name}}</p></b>
<form action="" method="post">
{% csrf_token %}
<input type="submit" name="{{z.id}}" value="ON"/>
<input type="submit" name="{{z.id}}" value="OFF"/><br>
<br>
<label>Tiempo</label>:
<input type="integerfield" name="Tiempo">
<input type="submit" name="{{z.id}}" value="Start">
</form>
{% endfor %}
</ul>
{% endif %}
In the views.py I have to change the 1 for something that dynamically represents the zone
views.py
def manual(request):
if request.POST.has_key('1'):
z = Zone.objects.get(id = 1)
keyword = request.POST.get("1","")
if keyword == "ON":
#do something
if keyword == "OFF":
#do something
if keyword == "Start":
#do something
zone_list = Zone.objects.all()
context = {'zone_list':zone_list}
return render(request, 'irrigation_controller/manual.html', context)
I solved the problem. As themanatuf said, I used a hidden input field with the zone_id.
manual.html
{% if zone_list %}
{% for z in zone_list %}
<b><p>{{z.name}}</p></b>
<form action="" method="post">
{% csrf_token %}
<input type="hidden" name="zone_id" value="{{z.id}}">
<input type="submit" name="order" value="ON"/>
<input type="submit" name="order" value="OFF"/><br>
<br>
<label>Tiempo</label>:
<input type="integerfield" name="Tiempo">
<input type="submit" name="order" value="Start">
</form>
{% endfor %}
{% endif %}
And in the view I read the zone_id and the order.
views.py
def manual(request):
if request.POST.has_key('zone_id'):
z = Zone.objects.get(id = request.POST.get("zone_id",""))
keyword = request.POST.get("order","")
if keyword == "ON":
z.irrigation_on()
if keyword == "OFF":
z.irrigation_off()
if keyword == "Start":
tiempo = request.POST['Tiempo']
tiempo = float(tiempo)
irrigation_time.delay(z.id, tiempo)
zone_list = Zone.objects.all()
context = {'zone_list':zone_list}
return render(request, 'irrigation_controller/manual.html', context)
Related
I am trying to write my own pagination in Python, Flask, SQLite and sqlalchemy. The idea is that when the "next_page" button is pressed, the code sends a query to the database and loads next results. The "previous" button takes the view back to the previous results.
At the moment the pagination works partially. If I press "next_page" once, nothing happens. If I press "next_page" a second time, the next results load correctly. But if I press "previous_page" then it takes me back to the first page (and it should take me back to the previous page).
I tried to add...
previous_page_number = int(request.args.get("previous_page_number", 0))
if not (page_number := previous_page_number):
page_number = 1
...but then the"next_page" button stops working completely.
Does anyone know what I'm missing here?
PYTHON
list_of_games = list_of_games.order_by(GamesDatabase.date_added)
next_page_number = int(request.args.get("next_page_number", 0))
# previous_page_number = int(request.args.get("previous_page_number", 0))
if not( page_number := next_page_number ):
page_number = 1
# if not( page_number := previous_page_number ) :
# page_number = 1
c = list_of_games.count()
if next_page_number * 8 < c:
has_next_page = True
else:
has_next_page = False
list_of_games = list_of_games.order_by(GamesDatabase.date_added)[(page_number-1)*8:(page_number)*8]
args = []
if request.args:
for arg, val in request.args.items():
args.append({"name": arg, "value": val})
if next_page_number >1:
has_prev_page = True
else:
has_prev_page = False
return render_template("test.html", list_of_games=list_of_games, args=args,
has_next_page=has_next_page, previous_page_number=page_number-1,
has_prev_page=has_prev_page, next_page_number=page_number+1)
HTML
</div>
{% if has_next_page %}
<form action="" method="GET">
{% for arg in args %}
{% if "next_page_number" != arg.name %}
{% if "previous_page_number" !=arg.name %}
<input type="hidden" name="{{ arg.name }}" value="{{ arg.value }}" >
{% endif %}
{% endif %}
{% endfor %}
<input type="hidden" name="next_page_number" value="{{ next_page_number }}" />
<button type="submit">Next page </button>
</form>
{% endif %}
{% if has_prev_page %}
<form action="" method="GET">
{% for arg in args %}
{% if "next_page_number" !=arg.name %}
{% if "previous_page_number" !=arg.name %}
<input type="hidden" name="{{ arg.name }}" value="{{ arg.value }}" >
{% endif %}
{% endif %}
{% endfor %}
<input type="hidden" name="previous_page_number" value="{{ previous_page_number }}" />
<button type="submit">Previous page </button>
</form>
{% endif %}
https://pastebin.com/QLv3CqZW
My form allows the user to enter a specific number of names for a specific number of basketball teams. These numbers are constantly updated so I need to create a dynamic form.
Let's say I have the following Flask view:
#app.route('/dynamic', methods=['GET', 'POST'])
def dynamic():
teams = ['Warriors', 'Cavs']
name_count = 2
return render_template('dynamic.html', teams=teams, name_count=name_count)
And the following form in the HTML template dynamic.html:
<form method='POST' action='/dynamic'>
{% for team_index in range(teams | count) %}
{% for name_index in range(name_count) %}
<input type="text"
class="form-control"
id="team{{ team_index }}_name{{ name_index }}"
name="team{{ team_index }}_name{{ name_index }}">
{% endfor %}
{% endfor %}
<form>
Which yields the following form:
<form method='POST' action='/dynamic'>
<input type="text" class="form-control" id="team0_name0" name="team0_name0">
<input type="text" class="form-control" id="team0_name1" name="team0_name1">
<input type="text" class="form-control" id="team1_name0" name="team1_name0">
<input type="text" class="form-control" id="team1_name1" name="team1_name1">
<form>
I love the Flask-WTF library so I'm wondering how I can use that (or simply wtforms) to render this form. I'm not sure this is even possible because wtforms requires a hardcoded field name for every input.
Figured this out. I need to use the WTForms Fieldlist and FormField enclosures.
class PlayerForm(FlaskForm):
player = Fieldlist(StringField('Player'))
class TeamForm(FlaskForm):
team = Fieldlist(FormField(PlayerForm))
#app.route('/dynamic', methods=['GET', 'POST'])
def dynamic():
teams = ['Warriors', 'Cavs']
name_count = 2
# Build dictionary to prepopulate form
prepop_data = {'team': [{'player': ['' for p in range(name_count)]} for team in teams]}
# Initialize form
form = TeamForm(data=prepop_data)
return render_template('dynamic.html', form=form)
And unpacking via jinja2 (id and name attributes on first field = team-0-player-0):
<form method="POST" action="/dynamic">
{{ form.csrf_token }}
{% for team in form.team %}
{{ team.csrf_token }}
{% for player in team.player %}
{{ render_field(player) }}
{% endfor %}
{% endfor %}
</form>
My HTML http://127.0.0.1:8000/orden-detalle/1
<form method="POST">
{% csrf_token %}
{% if orden.anulado == True %}
<ul>
<li><input id="estado_reanudar" name="estado" value="FALSE" type="radio">Anulado</li>
<input type="hidden" name="pk" value="{{ orden.pk }}">
</ul>
<ul>
<li>
<input type="submit" value="Reanudar Orden" />
</li>
</ul>
{% else %}
<ul>
<li><input id="estado_reanudar" name="estado" value="TRUE" type="radio">Activo</li>
<input type="hidden" name="pk" value="{{ orden.pk }}">
</ul>
<ul>
<li>
<input type="submit" value="Anular Orden" />
</li>
</ul>
{% endif %}
My views.py
def orden_detalle(request, pk=False):
if pk:
orden = get_object_or_404(Orden, pk=pk)
else:
orden = Orden()
if request.method == 'POST':
estado = request.POST.get('estado')
pk = request.POST.get('pk')
orden.anulado = estado
orden.save()
return HttpResponseRedirect(reverse('ordenes:orden_detalle', args=(pk)))
template = 'ordenes/orden_detalle.html'
return render(request, template, locals())
Terminal
[19/Nov/2015 16:03:17] "POST /orden-detalle/1 HTTP/1.1" 302 0
[19/Nov/2015 16:03:17] "GET /orden-detalle/1 HTTP/1.1" 200 2885
My urls.py
urlpatterns = [
url(r'^ordenes/$', views.orden_listado, name='orden_listado'),
url(r'^orden-detalle/(?P<pk>[-\d]+)$', views.orden_detalle,name='orden_detalle'),
]
When I change "estado" of "orden" using the form throws me the error 302.
It is supposed to be changing my html, but does not.
Where is the error?
Change the value in radio buttons:
<li><input id="estado_reanudar" name="estado" value="0" type="radio">Anulado</li>
<li><input id="estado_reanudar" name="estado" value="1" type="radio">Activo</li>
It works now. I modified my "view" to this:
def orden_detalle(request, pk=False):
if pk:
orden = get_object_or_404(Orden, pk=pk)
else:
orden = Orden()
if request.method == 'POST':
orden.anulado = not orden.anulado
orden.save()
return HttpResponseRedirect(reverse('ordenes:orden_detalle', args=(pk)))
template = 'ordenes/orden_detalle.html'
return render(request, template, locals())
And my html:
<form method="POST">
{% csrf_token %}
{% if orden.anulado == 1 %}
<ul>
<li>Anulado</li>
<li>
<input type="submit" value="Reanudar Orden" />
</li>
</ul>
{% else %}
<ul>
<li>Activo</li>
<li>
<input type="submit" value="Anular Orden" />
</li>
</ul>
{% endif %}
</form>
I assumed that the code 302 was a mistake, I was wrong. The documentation indicates that subclass HttpResponseRedirect returns an HTTP status code 302.
https://docs.djangoproject.com/en/1.8/ref/request-response/#django.http.HttpResponseRedirect
https://en.wikipedia.org/wiki/HTTP_302
This is my code:
views.py:
def some_function(request):
form = MyForm(request.POST)
if request.method == 'GET':
return render_to_response('template.html', RequestContext(request, {'form': form}))
elif request.method == 'POST':
input_word = request.POST['input_word']
if 'word_choice' in request.POST:
word_choice = request.POST['word_choice']
else:
word_choice = ''
var1 = HelperClass(input_word).func1()
table1 = HelperClass(input_word).table_one()
table2 = HelperClass(input_word).table_two()
word_selected = word_choice
content = {
'form': form,
'input_word': input_word,
'var1': var1,
'table1' : table1,
'table2' : table2,
'word_selected': word_selected,
}
return render_to_response('result_template.html', RequestContext(request, content))
else:
raise Http404
This is result_template.html:
{% block content %}
<form action="/admin/find-word/" method="post">
{% csrf_token %}
<input id="input_word" type="text" name="input_word" maxlength="100"><br />
<input type="submit" value="Submit" />
<form />
<h1>{% trans "You entered" %} "{{ input_word }}" </h1>
<p>{{ var1 }}</p>
<form action="/admin/find-root/" method="post">
{% csrf_token %}
<h3>{% trans "Table2" %}</h3>
{% for word in table2 %}
# Get info from database and display it on the current template.
<input type="radio" name='word_choice' value="{{ word }}"> {{ word }}<br>
{% endfor %}
<h3>{% trans "Table3" %}</h3>
{% for word in table3 %}
{# Get info from database and display it on the current template. #}
<input type="radio" name='word_choice' value="{{ word }}"> {{ word }}<br>
{% endfor %}
<p>{% trans "You selected: " %}{{ word_selected }}</p>
{# Submit the word of choice.#}
<input type="submit" value="Search">
<form />
{% endblock %}
I need to add code to views.py, so that:
it shows result, that was rendered after submitting the first form
(when assining input_word)
new result shows, when resubmitting the first form
when submitting second form redirect to success_template.html (this part I can do myself)
I know, that I need to use sessions here. I've tried different things, but I'm lost now.
Create a session variable in django as follows.
request.session['key'] = value
Access it by
request.session['key'] # or
request.session.get('key')
remove it by
del request.session['key']
In django you can simply assign values to sessions with:
request.session['value']
In your case you'd have to replace the word_selected variable with request.session['word_selected']
Have a form where user can change name on attribut Name and change which attribut a is connected to (attribut b).
Template:
"<form id="form1" name="form1" method="post" action="/define_a/{{c.id}}/edit/">
{% csrf_token %}
{% endblock %}
{% block buttons %}
<p><input type="submit" value="Save" /> Cancel
</p>
{% endblock %}
{% block a_rows %}
{% for a, a_form in a_list %}
<tr><td><img class="icon" src="{{images_dir}}/delete-icon.png"
onclick="javascript: return confirmDelete_name('Are you sure?
This will delete the stuff and all associated information.
The removal happens immediately and cannot be undone.', '{{a.id}}', 'delete');" />
</td><td>{{a_form.name}}</td>
<td>
<select name= "test">
<option value = "Null">None</option>
<option value = "{{a_form.id}}" selected>{{a.b}}</option>
{% for a, a_form in a_list %}
<option value = "{{a_form.id}}">{{a.name}}</option>
{% endfor %}"
View:
Checking that it is a post and that it is valid.
post = [myForm(request.POST, instance = test) for a in a's];
for p in post :
if not new_t.b == p:
if p == 'None':
new_t.b = None;
else:
new_t.b = p;
But i can't get all the values from the dropdown in the post.
I get all a.name in but only one value from the dropdown, sometimes I don't get any value at all.
Any ideas?