Django check if checkbox is selected - python

I'm currently working on a fairly simple django project and could use some help. Its just a simple database query front end.
Currently I am stuck on refining the search using checkboxes, radio buttons etc
The issue I'm having is figuring out how to know when a checkbox (or multiple) is selected. My code so far is as such:
views.py
def search(request):
if 'q' in request.GET:
q = request.GET['q']
if not q:
error = True;
elif len(q) > 22:
error = True;
else:
sequence = Targets.objects.filter(gene__icontains=q)
request.session[key] = pickle.dumps(sequence.query)
return render(request, 'result.html', {'sequence' : sequence, 'query' : q, 'error' : False})
return render(request, 'search.html', {'error': True})
search.html
<p>This is a test site</p></center>
<hr>
<center>
{% if error == true %}
<p><font color="red">Please enter a valid search term</p>
{% endif %}
<form action="" method="get">
<input type="text" name="q">
<input type="submit" value="Search"><br>
</form>
<form action="" method="post">
<input type='radio' name='locationbox' id='l_box1'> Display Location
<input type='radio' name='displaybox' id='d_box2'> Display Direction
</form>
</center>
My current idea is that I check which checkboxes/radio buttons are selected and depending which are, the right data will be queried and displayed in a table.
So specifically:
How do I check if specific check-boxes are checked? and how do I pass this information onto views.py

Radio Buttons:
In the HTML for your radio buttons, you need all related radio inputs to share the same name, have a predefined "value" attribute, and optimally, have a surrounding label tag, like this:
<form action="" method="post">
<label for="l_box1"><input type="radio" name="display_type" value="locationbox" id="l_box1">Display Location</label>
<label for="d_box2"><input type="radio" name="display_type" value="displaybox" id="d_box2"> Display Direction</label>
</form>
Then in your view, you can look up which was selected by checking for the shared "name" attribute in the POST data. It's value will be the associated "value" attribute of the HTML input tag:
# views.py
def my_view(request):
...
if request.method == "POST":
display_type = request.POST.get("display_type", None)
if display_type in ["locationbox", "displaybox"]:
# Handle whichever was selected here
# But, this is not the best way to do it. See below...
That works, but it requires manual checks. It's better to create a Django form first. Then Django will do those checks for you:
forms.py:
from django import forms
DISPLAY_CHOICES = (
("locationbox", "Display Location"),
("displaybox", "Display Direction")
)
class MyForm(forms.Form):
display_type = forms.ChoiceField(widget=forms.RadioSelect, choices=DISPLAY_CHOICES)
your_template.html:
<form action="" method="post">
{# This will display the radio button HTML for you #}
{{ form.as_p }}
{# You'll need a submit button or similar here to actually send the form #}
</form>
views.py:
from .forms import MyForm
from django.shortcuts import render
def my_view(request):
...
form = MyForm(request.POST or None)
if request.method == "POST":
# Have Django validate the form for you
if form.is_valid():
# The "display_type" key is now guaranteed to exist and
# guaranteed to be "displaybox" or "locationbox"
display_type = request.POST["display_type"]
...
# This will display the blank form for a GET request
# or show the errors on a POSTed form that was invalid
return render(request, 'your_template.html', {'form': form})
Checkboxes:
Checkboxes work like this:
forms.py:
class MyForm(forms.Form):
# For BooleanFields, required=False means that Django's validation
# will accept a checked or unchecked value, while required=True
# will validate that the user MUST check the box.
something_truthy = forms.BooleanField(required=False)
views.py:
def my_view(request):
...
form = MyForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
...
if request.POST["something_truthy"]:
# Checkbox was checked
...
Further reading:
https://docs.djangoproject.com/en/1.8/ref/forms/fields/#choicefield
https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#radioselect
https://docs.djangoproject.com/en/1.8/ref/forms/fields/#booleanfield

In models :
class Tag:
published = BooleanField()
(...)
In the template:
{% for tag in tags %}
<label class="checkbox">
<input type="checkbox" name="tag[]" value="" {% if tag.published %}checked{% endif %}>
</label>
{% endfor %}
Assuming you are sending the form as a POST, the values of the selected checkboxes are in request.POST.getlist('tag').
For example :
<input type="checkbox" name="tag[]" value="1" />
<input type="checkbox" name="tag[]" value="2" />
<input type="checkbox" name="tag[]" value="3" />
<input type="checkbox" name="tag[]" value="4" />
Say if 1,4 were checked,
check_values = request.POST.getlist('tag')
check_values will contain [1,4] (those values that were checked)

{% for tag in tags %}
<label class="checkbox">
<input type="checkbox" name="tag[]" value=""
{% if tag.published %}checked{% endif %}>
</label>
{% endfor %}
<input type="checkbox" name="tag[]" value="1" />
<input type="checkbox" name="tag[]" value="2" />
<input type="checkbox" name="tag[]" value="3" />
<input type="checkbox" name="tag[]" value="4" />

Related

How to render results from API based on the user's search using Django

As you can see in the picture below I'm trying to have the user search for a given country, start/end date and get the result of "Confirmed Cases" and "Date" back from the API, but I'm not sure how to do it.
I tried using this API, to fill the drop-down menu of the countries -->
https://api.covid19api.com/summary
but this is the other API that I have to use but while changing the parameters for the country and dates -->
https://api.covid19api.com/country/afghanistan/status/confirmed?from=2020-09-06T00:00:00Z&to=2020-09-11T00:00:00Z
Here are snippets of my code:
views.py
def home(request):
# second_response = requests.get('https://api.covid19api.com/country/afghanistan/status/confirmed?from=2020-09-06T00:00:00Z&to=2020-09-11T00:00:00Z').json()
second_response = requests.get('https://api.covid19api.com/summary').json()
my_list = []
for i in range(0, len(second_response['Countries'])):
my_list.append(second_response['Countries'][i]['Country'])
if request.method=='POST':
selected_country = request.POST['selected_country']
print('here', selected_country)
return render(request, 'home.html', {'my_list': my_list})
home.html
<div class="container justify-content-center">
<form action="{% url 'home' %}" method="post">
{% csrf_token %}
<label for="selected_country" style="margin-right: 5px;"> Select a Country, Start & End Dates : </label>
<select name="selected_country" >
{% for object in my_list %}
<option value="">{{object}}</option>
{% endfor %}
</select>
<label for="startdate"></label>
<input type="date" id="startdate">
<label for="enddate"></label>
<input type="date" id="enddate">
<input type="submit" value="Search" />
</form>
</div>
PLUS: when I click on "search" i should get the value of the selected_country because I tried printing it, but it doesn't show for some reason, so the method is post but for some reason I can't get back the selected_country
Any help is appreciated
JAVASCRIPT
if you have any solid grasp of javascript i recommend you do that in javascript, because it will just make it better and easier
otherwise :
view.py
def handler(request):
if request.method=='POST':
selected_country = request.POST['selected_country']
startDate= request.POST['startdate']
endDate= request.POST['enddate']
request_handler = requests.get(f"https://api.covid19api.com/country/{selected_country}/status/confirmed?from={startDate}T00:00:00Z&to={endDate}T00:00:00Z")
if request_handler.status_code=200:
#To prevent errors
request_json=request_handler.json()
else:
pass # do something
return render(request, 'result.html', {"json":request_json})
#you should handle the data at the front end using jinja blocks
note : i don't know much about Django so the code may break

Django Form processing files

So I have the following code:
# the view
class UpdateDateView(LoginRequiredMixin, UpdateView):
model = Date
form_class = DateForm
template_name = 'app/form/date_edit_form.html'
def save_photos(self, date) -> None:
photos = self.request.FILES.getlist('photo')
current_photos = self.request.FILES.getlist('custom-photo-name') # this is not working
for photo in photos:
Photo.objects.create(date=date, photo=photo)
def form_valid(self, form):
date = form.save()
self.save_photos(date)
return super().form_valid(form)
# the form
class DateForm(forms.ModelForm):
photo = forms.ImageField(required=False)
class Meta:
model = Date
exclude = ('user',)
# the Edit form
<form action="{% url 'app:edit-date' date.slug %}" method="post" enctype="multipart/form-data">{% csrf_token %}
<div class="form-container">
...
<tr>
<th><label for="id_photo">Image:</label></th>
<td>
<input type="file" name="photo" accept="image/*" id="id_photo" multiple>
</td>
</tr>
<div class="current-photos">
{% for photo in date.photos.all %}
<div class="photo-wrapper-{{ forloop.counter }}">
<img src="{{ photo.photo.url }}" width="200px"><a class="delete-photo" id="{{ forloop.counter }}">Delete</a>
<input type="file" name="custom-photo-name" value="{{ photo }}" class="hide" id="photo_{{ forloop.counter }}">
</div>
{% endfor %}
</div>
</div>
<div class="buttons">
<input type="submit" value="Save" class="create-button redirection no_decoration">
Back
</div>
</form>
# js (jquery)
$('.delete-photo').on('click', function() {
const id = $(this).attr('id');
const div_class = `.photo-wrapper-${id}`;
$(div_class).remove()
});
I have a CreateView and UpdateView. The ImageField is not required, it is optional.
Let's assume I have created a new date with photos. Then I wanted to edit its pictures (delete some and add some new). When I click on tag (Delete), the div wrapper for that photo is being removed. When I try to save my edits, I want to access 2 different lists with photos (ones which were added in the past, and the new photos).
This self.request.FILES.getlist('custom-photo-name') seems to do nothing with current photos. Please help, maybe my code logic is bad in general? What I am missing here? What html form looks for when I submit the form, whether for the tag or maybe name attribute? Huge thanks in advance!

how can i insert dynamic fields of a form in django into database

I have a form with checkbox inputs the number of inputs is dynamic because i get it from the database,in my form i might have 2 or 3 or N .. checkboxes. From these input the user will check some or all of them and then he click the submit button.
The problem is that only one input is saved into database
<form method="post" action="createQcm">
{% csrf_token %}
{% for mati in quest %}
<INPUT type="checkbox" value ="{{mati.id_question }}" name="choix" >
{{mati.questionA }}</input></br></br>
{% endfor %}
<input type="hidden" name="s" value="{{idQ}}" readonly>
the view:
def createQcm(request):
q=request.POST["choix"]
r=request.POST["s"]
rep = contenir(idQuestion=q,idQuiz=r)
rep.save()
return render(request,'myblog/subject.html')
How can I save them all?

Django form with checkbox is always False

I'm looking to create a Django form with a checkbox.Irrespective of weather I check or uncheck the box,it is not detected in POST request.Here is the code of the template-
<form action="annotate_page" method="post">{% csrf_token %}
<input id="repeat" type="checkbox" >
<label for="repeat">Repeat Sentence?</label>
<br>
<button type="submit">Next</button><br>
</form>
Here is my forms.py-
from django import forms
class AnnotateForm(forms.Form):
repeat=forms.BooleanField(required=False)
Here is my views logic-
if request.method=="POST":
form = AnnotateForm(request.POST)
if form.is_valid():
print(request.POST)#prints only csrf_token in Query_dict
print(form.cleaned_data["repeat"])#Always false
Irrespective of weather the checkbox is checked or not,the print statement always gives False.
I know there are questions similar,but they don't solve my problem.
<form action="annotate_page" method="post">{% csrf_token %}
<input id="repeat" name="something" type="checkbox" >
<label for="repeat">Repeat Sentence?</label>
<br>
<button type="submit">Next</button><br>
</form>
and in view
if request.method=="POST":
form = AnnotateForm(request.POST)
if form.is_valid():
print(request.POST)#prints only csrf_token in Query_dict
print(form.cleaned_data["something"])#Always false
you need to give a name in the input field or else it wont be captured

Bootstrap variable passed over to Flask

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}}

Categories

Resources