how to access radio button selected value in Django - python

I am trying to access radio button selected value in my django view but it returns on instead of selected value.
Template form
<form class="col-md-8 mx-auto" action="upload" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group" id="div_id_sample" >
<label for="id_sample" class="col-form-label requiredField">Select File</label><br>
<div class="btn btn-primary">
<input type="file" name="sample" class="clearablefileinput" required id="id_sample" accept=".exe">
</div>
</div>
<div class="form-group">
<label for="radiogroup">Enforce Timeout</label><br>
<div class="btn-group" data-toggle="buttons" id="radiogroup">
<label class="btn btn-secondary">
<input type="radio" name="timeoptions" id="option60" autocomplete="off" value="60"> 60 seconds
</label>
<label class="btn btn-secondary">
<input type="radio" name="timeoptions" id="option120" autocomplete="off" value="120"> 120 seconds
</label>
<label class="btn btn-secondary active">
<input type="radio" name="timeoptions" id="option180" autocomplete="off" checked value="180"> 180 seconds
</label>
</div>
</div>
<div class="form-group">
<label for="radiogroup2">Select Machine:</label><br>
<div class="btn-group" data-toggle="buttons" id="radiogroup2">
<label class="btn btn-secondary">
<input type="radio" name="machineoptions" id="machine1" autocomplete="off" value="0"> Windows XP
</label>
<label class="btn btn-secondary active">
<input type="radio" name="machineoptions" id="machine2" autocomplete="off" value="1" checked> Windows 7
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
views.py
in my views i am using ModelForm but not in my HTML and the reason behind that is i copied and pasted the htmlcode generated by the ModelForm. Reason is because i need to collect two more items that are not in my data MODEL so that why.
def upload(request):
if request.user.is_authenticated:
if request.method == 'POST':
file = request.FILES['sample']
form = SampleForm(request.POST, request.FILES)
if form.is_valid():
new_sample = form.save(commit=False)
new_sample.file_name = file.name
new_sample.user = request.user
print(request.POST)
TimeOut = request.POST.get('timeoptions')
machine = request.POST.get('machineoptions')
print(TimeOut)
print(machine)
form.save()
return redirect('reports')
else:
messages.info(request,'Invalid Form')
else:
form = SampleForm()
if request.method == 'GET':
return render(request, 'upload2.html', {'form': form})
else:
return redirect(reverse('login'))
Print output
<QueryDict: {'csrfmiddlewaretoken': ['VvAqdOp8RrpKOgwxLD2dpGartPvUrTHTg9AUbqsX6vphxdojTJqn7tsvLCkneWOm'], 'timeoptions': ['on'], 'machineoptions': ['on']}>
on
on
I am just trying to access the selected button value.

I guess this is mostly because you are enclosing the <input> tag inside the <label> tag.Also you must give the for attribute for and put the input element's id in the <label> tag
Try like this:
<label class="btn btn-secondary" for="option60">60 seconds</label>
<input type="radio" name="timeoptions" id="option60" autocomplete="off" value="60">
You can do this for all the radio buttons.Then in your view you can access with TimeOut = request.POST.get('timeoptions')

Related

Using django form within custom html template

I have a html file that I wanna use this template to render my form and save it to my database
How to do this?
HTML code:
<div class="container-contact100">
<div class="wrap-contact100">
<form class="contact100-form validate-form" enctype="multipart/form-data" method="POST">
{% csrf_token %}
<span class="contact100-form-title">
Add Item!
</span>
<div class="wrap-input100 validate-input" data-validate="Name is required">
<span class="label-input100">Title</span>
<input class="input100" type="text" name="name" placeholder="Enter food name">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input">
<span class="label-input100">Price</span>
<input class="input100" type="number" name="price" placeholder="Enter food price">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Message is required">
<span class="label-input100">Description</span>
<textarea class="input100" name="message" placeholder="Your description here..."></textarea>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate="Image is required">
<input type="file" class="custom-file-input" id="customFile" name="filename">
<label class="custom-file-label" for="customFile">Choose file</label>
<span class="focus-input100"></span>
</div>
<div class="container-contact100-form-btn">
<div class="wrap-contact100-form-btn">
<div class="contact100-form-bgbtn"></div>
<button class="contact100-form-btn" type="submit">
<span>
Add
<i class="fa fa-long-arrow-right m-l-7" aria-hidden="true"></i>
</span>
</button>
</div>
</div>
</form>
</div>
</div>
<div id="dropDownSelect1"></div>
and here is my forms.py :
from django import forms
from .models import Product
class AddItemForm(forms.ModelForm):
class Meta:
model = Product
fields = '__all__'
even you can access my project from this link via github:
https://github.com/imanashoorii/FoodMenu.git
You have to set the name attributes in your form in your html according to field names of your Porudct model like this (using data from your GitHub link):
add_product.html
<form method="post" enctype="multipart/form-data"> # here define enctype attribute so your form can accept images
{% csrf_token %}
<input type="text" name="title">
<input type="text" name="description">
<input type="number" name="price">
<input type="file" name="image">
<button type="submit">Submit</button>
</form>
Or instead of manually defining each field you can just pass a {{ form.as_p }} to your html to render each field inside a <p> tag like this:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
Then here is how you would save it in a view:
views.py
def add_product(request):
if request.method == 'POST':
form = AddItemForm(request.POST, request.FILES) # request.FILES is so your form can save images
if form.is_valid()
form.save()
return redirect('home') # redirect to a valid page
else:
form = AddItemForm()
return render(request, 'add_product.html', {'form': form})
I have fixed my problem by changing views.py to this and fix it :
if form.is_valid():
title = request.POST.get('title')
description = request.POST.get('description')
price = request.POST.get('price')
image = request.POST.get('image')
form.save()
return redirect("food:home")

form.is_valid() not working when using django forms for updating information to the databse

So I wanna be able to update information of a router in the database using a form, I wanna have a form pre-populated with that specific router details. The problem is that form.is_valid() is not working
I tried using {{ form.errors }} {{ form.non_field_errors }} and print(form.errors) but none of them worked
views.py (incomplete)
def info_router(request, pk):
rout = Routers.objects.get(sn=pk)
if request.method == 'GET': # Insert the info in forms
form = UpdateRouter()
rout = Routers.objects.get(sn=pk)
args = {'router': rout}
return render(request, "router_info.html", args)
if request.POST.get('delete'):
# Delete router
rout.delete()
messages.warning(request, 'Router was deleted from the database!')
return redirect("db_router")
if request.method == 'POST':
#Updating the form
form = UpdateRouter(instance=Routers.objects.get(sn=pk))
print(form)
print(form.errors)
if form.is_valid():
data = UpdateRouter.cleaned_data
mac = data['mac']
print(mac)
return HttpResponseRedirect('db_router')
else:
print("Invalid form")
return render(request, "db_router.html", {'form': form})
forms.py
class UpdateRouter(ModelForm):
class Meta:
model = Routers
fields = ['model', 'ip_addr', 'name', 'sn', 'mac']
template
<form class="form-horizontal" action="" method="post">
{% csrf_token %}
<div class="form-group"> <!-- Form with the router details -->
<label class="control-label col-sm-2" for="text">Serial number:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" name="sn" value="{{ router.sn }}" readonly>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Model:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.model }}" name="model" readonly>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Ip address:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.ip_addr }}" name="ip_addr">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.name }}" name="name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Mac address:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.mac }}" name="mac">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Extra info:</label>
<div class="col-sm-10">
<textarea class="form-control" name="extra_info" id="FormControlTextarea" rows="3">Example of some info</textarea>
</div>
</div>
<div class="form-group" style="margin-top: 20px;">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Update</button> <!-- Responsible for updating the router -->
Cancel
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#myModal" style="float: right"> <!-- Responsible for the delete modal to open -->
Delete
</button>
</div>
</div>
</form>
You never passed request.POST and rquest.FILES. If you want to update the fields and files, you need to form.save() your form:
if request.method == 'POST':
#Updating the form
form = UpdateRouter(request.POST, request.FILES, instance=Routers.objects.get(sn=pk))
print(form)
print(form.errors)
if form.is_valid():
data = form.cleaned_data
mac = data['mac']
form.save()
print(mac)
return redirect('db_router')
else:
print("Invalid form")
If you do not pass request.POST and/or request.FILES, then Django does not consider the form filled in, and it is never considered valid.
If you pass both files and data, then you need to add the enctype="multipart/form-data" to your <form> tag:
<form enctype="multipart/form-data" class="form-horizontal" action="" method="post">
<!-- -->
</form>
you need to create a bound_form
form = UpdateRouter(request.POST)
form = UpdateRouter(request.POST) binds the data to the form class. then validate
the inputs using is_valid().

Pass selected option value from select tag in python flask

I have a user registration form which has a select tag. I want the value from the selected option to be assigned to a variable(the code is shown below).
registration.html
<form method="POST" action="/register">
<div class="form-group">
{{render_field(form.name, class_="form-control", placeholder="Name")}}
</div>
<div class="form-group">
{{render_field(form.email, class_="form-control",placeholder="Email")}}
</div>
<div class="form-group">
{{render_field(form.username, class_="form-control", placeholder="Username")}}
</div>
<div class="form-group">
{{render_field(form.password, class_="form-control", placeholder="Password")}}
</div>
<div class="form-group">
{{render_field(form.confirm, class_="form-control", placeholder="Re-enter Password")}}
</div>
<div class="form-group">
<p>I prefer to : </p>
<select id= "studenttype" name="studenttype">
<input type="radio" name="Theorist" value="Theorist"><span>Read lecture notes</span><br/>
<input type="radio" name="Theorist" value="Activist"><span>Watch videos</span>
</select>
</div>
<input type="submit" class="btn btn-success" value="Submit">
<p>Register as Instructor </p>
</form>
I have used the following code to assign the selected option value to the variable learning_style.
app.py
#app.route('/register', methods=['GET', 'POST'])
def register():
learning_style = request.form.get("studenttype")
form = RegisterForm(request.form)
if request.method == "POST" and form.validate():
name = form.name.data
email = form.email.data
username = form.username.data
password = form.password.data
user_type = 'student'
print(learning_style)
...........
flash('You are now registered', 'success')
redirect(url_for('index'))
return render_template('register.html', form=form)
But this doesn't seem to work. Any help is much appreciated. Thanks.
You are mixing up radio buttons and select dropdowns.
Change this in your template from:
<select id= "studenttype" name="studenttype">
<input type="radio" name="Theorist" value="Theorist"><span>Read lecture notes</span><br/>
<input type="radio" name="Theorist" value="Activist"><span>Watch videos</span>
</select>
to:
<input type="radio" name="Theorist" value="Theorist"><span>Read lecture notes</span><br/>
<input type="radio" name="Theorist" value="Activist"><span>Watch videos</span>
And in your app:
learning_style = request.form.get("Theorist")

How to get checked multiple radio input value in flask?

I am making a quiz app. I want to send back the values of checked radio inputs after form has been submitted.Howto send the values in dict format. like this: { 1:A,2:B...}
FLASK
app.route('/test', methods=['GET','POST'])
#is_logged_in
def test():
if request.method == 'POST':
app.logger.info(request.form)//What to do here?
#create cursor
cur=mysql.connection.cursor()
cur.execute("SELECT * FROM questions")
data = cur.fetchall()
return render_template('quiz.html', data=data)
HTML
<form action="" class="text-left ml-4" method="POST">
{% for i in data %}
<h5>{{i['id']}}. {{i['question']}}</h5>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="radio" name="option" value="A"
> {{i['chA']}}
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="radio" name="option" value="B">{{i['chB']}}
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="radio" name="option" value="C" > {{i['chC']}}
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="radio" name="option" value="D" > {{i['chD']}}
</label>
</div>
<br>
{% endfor%}
<div class="col-md-12 text-center mb-1">
<button type="submit" class="btn-new btn-lg"> Submit </button>

How to post data via form HTML?

I want to post the data to the server via form. How can I do this?
<div class="panel-body">
<form role="form" action="{% url 'login' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="sender-email" class="control-label">Username:</label>
<div class="input-icon"> <i class="icon-user fa"></i>
<input id="sender-email" type="text" placeholder="Username" class="form-control email">
</div>
</div>
<div class="form-group">
<label for="user-pass" class="control-label">Password:</label>
<div class="input-icon"> <i class="icon-lock fa"></i>
<input type="password" class="form-control" placeholder="Password" id="user-pass">
</div>
</div>
<div class="form-group">
<input class="btn btn-primary btn-block" id="authenticate_user" type="submit" value="Submit">
</div>
</form>
</div>
My views.py
#csrf_exempt
def signin(request):
if request.method == 'POST':
print request.POST.get('sender-email') #prints None
username = request.POST['username'] # throws error, username not available.
password = request.POST['password']
How do I post the data without using jquery? I know of a way of posting through AJAX jquery, but dont wanna do that.
The 'name' attribute of input tags is set as keys of request.GET and request.POST.
Add name attribute to all your input tags.
<input name="username" id="sender-email" type="text" placeholder="Username" class="form-control email">
<input name="password" type="password" class="form-control" placeholder="Password" id="user-pass" >
POST data are populated using the name attribute of your input elements. Change your id attributes or add a name one accordingly. E.g:
<input type="password" class="form-control" placeholder="Password" name="user-pass">
You should also consider using a form to handle your data more easily.

Categories