Detect if checkbox is ticked? - python

In django I do the following to get the value of an text box for example:
On my HTML page:
<input type="text" name="inputBox" id="inputBox" />
ON the views.py page:
valueOfTextBox= request.POST.get('inputBox', False)
How do I get whether a ceck box is 'checked' or not??
<input type="checkbox" id="selectAll">

If the inputBox is included in request.POST it has been checked. Therefore you could do the following.
if request.POST.get('selectAll', False):
...do stuff...
See this answer for details.

It's exactly the same, just write:
request.POST.get('selectAll', False)

You don't have value="" attribute on you checkbox so in case it is checked, your POST variable will have value 'on', if not checked, the variable will not be in your POST dict. So you can check it like described in previous answers.
PS: You don't need to write False as the second parameter to get() method, it will automatically return None what is in boolean the same as False.

Related

Submit form that uses Intercooler in Django StaticLiveServerTestCase

I am trying to write a selenium test for the submission of a form, which uses intercooler.js when it is submitted. The main problem I am having, is that when I navigate to the page, the form has class="disabled", which is not expected behaviour, and I can't submit the form. The relevant part from the intercooler docs says:
By default, intercooler will apply the disabled class to the element
that triggers an intercooler request. This can be used to give a
visual hint to the user that they should not click or otherwise
trigger the request again, and is Bootstrap-friendly.
However, it seems to me that the disabled class is being added to the form element before I actually submit the form, and as I understand it should only be added after a request is in-flight.
The form currently looks like this:
<form ic-post-to="/dashboard/calculate/2/exports/" ic-select-from-response="#content" ic-target="#content" method="post" ic-src="/dashboard/calculate/2/exports/" ic-verb="POST" ic-trigger-on="default" ic-deps="ignore" class="disabled">
<input type="hidden" name="csrfmiddlewaretoken" value="...">
<input type="submit" name="new" value="New" class="btn btn-primary float-right ml-1" id="submit-id-new">
</form>
I have tried adding explicit and implicit waits so that the entire page will load but the problem is still there.
Any help with this would be much appreciated.
Try to use Javascript to click on the button:
submit = driver.find_element_by_id("submit-id-new")
driver.execute_script("arguments[0].click();", submit)
It turns out that I was waiting in the wrong place. Instead of waiting when the page loads, I should have been waiting after the form was submitted to allow the page content to be updated.

Add editable choices in django

I am trying to add a editable choicefield in django like the picture, already do some research on this. Unfortunately, the solution like django-autocomplete doesn't quite fulfill my needs. The autocomplete looks fine, but if do so, I need create a django modal to generate the choices through a url view request, but in my case, it doesn't necessary to do that, I just need put these 3 choices for ip address in the dropdown list, and choose one of them then edit it or submit.
The solutions I found, but they are not very well fit my need:
Django admin: Change selected box of related fields to autocomplete
Django editable dropdown field
If you want to use just those three entries the quickest way is to use a datalist, it just needs to be added into your HTML somewhere.
<div id="page-wrapper">
<label for="ip">Network address</label>
<input type="text" id="ip" list="ip-datalist">
<datalist id="ip-datalist">
<option>192.168.0.0/24</option>
<option>10.0.0.0/24</option>
<option>172.16.0.0/24</option>
</datalist>
</div>
If your options are likely to never change, you could hardcode them into your html like the answer above. If you're generating your dropdown using a form however it would be better to do something like this:
class MyForm(forms.Form):
ip_list = ((1, '192.168.0.0/24'), (2, '10.0.0.0/24'),
(3, '172.16.0.0/24'), )
network_address = forms.ChoiceField(label='Network Address',
choices=ip_list)
...
Once you render the form object in your template it ends up producing html like this:
<label for="id_network_address">Network Address:</label>
<select id="id_network_address" name="network_address">
<option value="1">192.168.0.0/24</option>
<option value="2">10.0.0.0/24</option>
<option value="3">172.16.0.0/24</option>
</select>
This way it is easier to change the ip_list in future if you need to, plus its keeps all your code in one place. This is explained in the docs here.

How to use GET method on checkbox in Python 2.7

Hello I am trying to use the .GET form method on a check box, select tag and radio button in Python2.7 utilising google app engine and thats it.
here is the code so far
HTML
<form method='GET'>
<input type="checkbox" name="name" value="checkbox">
<select name='select'>
</form>
Python Code
select = self.request.GET['select']
checkbox = self.request.GET['name']
This works for my standard input fields (such as text) but not on any other type of input I use. I have looked everywhere for the documentation on this but have come up empty, any help would be appreciated.
Thanks in advance!
When a checkbox is not checked, the browser doesn't send the field.
GET is a MultiDict object, which acts just like a dictionary. As such you can use containment testing with in to see if the checkbox is present in the request:
checkbox = 'name' in self.request.GET
This sets a boolean True or False.
Alternatively, test for it instead with the .get() method:
checkbox = bool(self.request.GET.get('name'))
GET.get('name') returns None (a false value) if the checkbox is missing from the request, otherwise it'll return 'checkbox' (a true value).
For <select> elements, if none of the options are selected, it too is omitted from the request. If there is a default value you'd pick, then you can do so with:
select = self.request.GET.get('select', 'default value')
For the precise rules as to what a browser will include in the form, see the Successful controls specification; only controls that are successful are included.

Flask: how to implement a general searchbar for every view, without rewriting it?

I have a Problem to implement my search bar. I have it in my base template, an get a returnvalue over the get attribute ?search=
my Problem is now, that I want to use the searchbar from every site in my project without rewrite the searchcall in every single view.
is there a way to only write it once?
If it helps, my searchbarcode:
<input class="form-control" name="search" placeholder="Search Here" autocomplete="off" autofocus="autofocus" type="text">
Add an action attribute to your form tag. This will allow you to point all searches at one view.
<form action="{{ url_for('search') }}">
You can then include something along these lines with your views.
#app.route('/search')
def search():
query = request.args('search')
Quick update to the above, it looks like later versions of Flask needs different syntax.
#app.route('/search')
def search():
query = request.args('search')
throws
TypeError: 'ImmutableMultiDict' object is not callable
I used square brackets around the args instead and that resolved the error
#app.route('/search')
def search():
query = request.args['search']

dynamic forms in django with ajax/dajax

I have this simple form with a queryset to display job objects and allow the user to select one. Now, i would like to have a group of two radio buttons that would allow the user to select a 'filtering option'. If the user selects a group filter with the radio buttons, i would a drop down to appear that allows them to select which group they would like to filter on. I want to do this without having to reload the page, so i'm attempting to use dajax.
I was able to find an example on the dajax website that does something similiar, however, i was not able to get it to work. The radio buttons appear and the drop down appears(empty). When i click on the "Group" radio button, the drop-down should populate with all my Group objects, but it doesnt.
I've been stuck on this for awhile, so any help would be greatly appreciated.
forms.py
filters = (('0', 'Group'),
('1', 'Host'),
)
class JobSelectForm(forms.Form):
def __init__(self, *args, **kwargs):
super(JobSelectForm, self).__init__(*args, **kwargs)
self.fields['jobs'].widget.attrs["size"] = 20
jobs = forms.ModelChoiceField(queryset=Job.objects.all().order_by('name'), empty_label=None,)
filter = forms.ChoiceField(choices=filters,
widget=forms.RadioSelect(attrs={'onchange': "Dajaxice.tdportal.updatefilter(Dajax.process,{'option':this.value})", 'name':'combo1', 'id':'combo1', },
renderer=HorizRadioRenderer),
ajax.py
def updatefilter(request, option):
dajax = Dajax()
options = [Group.objects.all(),
Host.objects.all(),
]
out = ""
for o in options[int(option)]:
out = "%s<option value='#'>%s" % (out,o,)
dajax.assign('#combo2','innerHTML',out)
return dajax.json()
dajaxice_functions.register(updatefilter)
template
{{selectForm.filter.label}}: {{selectForm.filter}}
<br>
<select name="combo2" id="combo2" onchange="" size="1"></select>
<br><br>
<form method="post" action="/tdportal/jobs/">{% csrf_token %}
{{selectForm.jobs}}
<br><br>
<input type="submit" value="Edit" /> <input type="button" name="new" value="New" />
</form>
You need to add your dajaxice function to the select onchange to reference your function in the template.
Something like:
<select name="combo2" id="combo2" onchange="Dajaxice.your_project.your_appname.updatefilter(Dajax.process,{'option':this.value}" size="1"></select>
(Replace your_project with your project name, your_app with your appname).
Also make sure in your template you have all the necessary headers (and that they actually are there; e.g., if you view the source that you can click to them).
Be sure to debug using google chrome inspector (Ctrl-Shift-I) or firebug (in firefox).
EDIT: I now noticed that you have something similar that's in your form. How does it render in the HTML when you view the source? Is it improperly escaped?
I think you forgot a % sign (value='#') and a closing </option> in here:
out = "%s<option value='%s'>%s</option>" % (out,o,o)

Categories

Resources