I have 5 radio buttons and each have different values but as user can only select 1 option out of 5 and after selecting the value of radio button should be stored in my django models.
This is my html code
<div class="col">
<div class="form-group">
<input class="form-check-input" type="radio" name="reason" id="reason1" checked>
<label class="form-check-label" for="reason1">
Casual Leave
</label>
</div>
<div class="form-group">
<input class="form-check-input" type="radio" name="reason" id="reason2">
<label class="form-check-label" for="reason2">
Medical Leave
</label>
</div>
<div class="form-group">
<input class="form-check-input" type="radio" name="reason" id="reason3">
<label class="form-check-label" for="reason3">
Earned Leave
</label>
</div>
<div class="form-group">
<input class="form-check-input" type="radio" name="reason" id="reason4">
<label class="form-check-label" for="reason4">
Office Duty
</label>
</div>
<div class="form-group">
<input class="form-check-input" type="radio" name="reason" id="reason5">
<label class="form-check-label" for="reason5">
Compensatory Off
</label>
</div>
</div>
*this code contains form tag
My Django function
def leaveapplicationsubmit(request):
if request.method == 'POST':
reason1 = request.POST['reason1']
reason2 = request.POST['reason2']
reason3 = request.POST['reason3']
reason4 = request.POST['reason4']
reason5 = request.POST['reason5']
if 'reason1' in request.POST:
reason = "Casual Leave"
elif 'reason2' in request.POST:
reason="Medical Leave"
elif 'reason3' in request.POST:
reason="Earned Leave"
elif 'reason4' in request.POST:
reason="Office Duty"
elif 'reason5' in request.POST:
reason="Compensatory Off"
else:
return HttpResponse('Please select the reason')
else:
return HttpResponse("Failed")
Please help me with it, I really need that
All of the buttons have name="reason". That is the name you should look for in the code, not reason1, reason2 etc. Those are ids, not names.
Also, each button needs a value attribute, so you can tell which one was pressed.
Look at the examples here https://www.w3schools.com/tags/att_input_type_radio.asp
In views write this code, here reason_ will hold the value which will be selected by the user and in HTML code write it as given here https://www.w3schools.com/tags/att_input_type_radio.asp then reason_ will hold the value of the selected option
def radio(request):
if request.method == "POST":
d = request.POST
for key,value in d.items():
if key == "reason":
reason_ = value
Related
I am working on a small django-python project which has two models "staff_type" and "staff". In the staff_type model, only designation and date fields are populated. And in the staff model, there is OneToOneField relation of staff_type. Means whenever a user want to add staff first he/she will have to add staff_type and then in the staff module, user will choose the staff type (designation) from a select menu in which all the staff_type are shown respectively.
Now, whenever a user select any designation (staff_type) and fill the entire form, I want to store the selected staff_type id in the staff model/table.
Note: I have tried this from django admin, and it works perfectly but I want to do the same work in my own designed templates.
Modles.py
class staff_type(models.Model):
designation = models.CharField(max_length=50)
salary = models.IntegerField()
datetime = models.DateTimeField()
entrydatetime = models.DateTimeField( auto_now=False, auto_now_add=False)
class staff(models.Model):
staff_type = models.OneToOneField(staff_type, on_delete=models.CASCADE)
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
fathername = models.CharField(max_length=50)
city = models.CharField(max_length=50)
country = models.CharField(max_length=50)
state = models.CharField(max_length=50)
zip = models.IntegerField(blank=True)
address = models.CharField(max_length=100)
contact =models.CharField(max_length=20)
cnic = models.CharField(max_length=14)
photo = models.ImageField()
cv = models.ImageField()
otherfiles = models.ImageField()
views.py
def add_staff_type(request):
if request.method == 'POST':
designation = request.POST.get('designation')
salary = request.POST.get('salary')
datetime = request.POST.get('datetime')
add_staff_type = staff_type.objects.create(designation=designation, salary=salary, datetime=datetime, entrydatetime = dt.now())
add_staff_type.save()
messages.info(request, "Staff type has been Added.")
return redirect('add_staff_type')
else:
#fetching records from the database table
display_staff_type = staff_type.objects.all()
return render(request, 'staff/staff_type.html',{'display_staff_type':display_staff_type})
#this view is for fetching the designation column and displaying in the select tag
#and rendering add_staff html form
def add_staff(request):
staff = staff_type.objects.all()
return render(request, 'staff/add_staff.html', {'staff':staff})
#this view is for adding the staff
def add_staff_view(request):
if request.method == 'POST':
staff_type = request.POST.get('stafftype')
firstname = request.POST.get('firstname')
lastname = request.POST.get('lastname')
fathername = request.POST.get('fathername')
city = request.POST.get('city')
country = request.POST.get('country')
state = request.POST.get('state')
zipcode = request.POST.get('zip')
contact = request.POST.get('contact')
cnic = request.POST.get('cnic')
address = request.POST.get('address')
photo = request.FILES.get('photo')
cv = request.FILES.get('cv')
otherfiles = request.FILES.get('photo')
add_staff = staff.objects.create(firstname=firstname, lastname=lastname, fathername=fathername, city=city,country=country, state=state, contact=contact, cnic=cnic, zip=zipcode, address=address, photo=photo, cv=cv, otherfiles=otherfiles, staff_type=staff_type)
add_staff.save()
messages.info(request, "Staff has been Added.")
return redirect('add_staff')
else:
return render(request, 'staff/add_staff.html')
urls.py
urlpatterns = [
path("", views.index, name="index"),
path("staff/add_staff_type", views.add_staff_type, name="add_staff_type"),
path("staff/add_staff", views.add_staff, name="add_staff"),
path("staff/add_staff_view", views.add_staff_view, name="add_staff_view"),
]
add_staff.html
<form class="needs-validation" action="add_staff_view" method="POST" enctype="multipart/form-data" novalidate>
{% csrf_token %}
<div class="card-body">
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="validationCustom01">Staff Type</label>
<select class="form-control" id="validationCustom01" name="stafftype">
{% for staff in staff %}
<option name="stafftype" value="{{ staff.id }}" required>{{staff.designation}}</option>
{% endfor %}
</select>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom02">First name</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="First name" name="firstname" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom03">Last name</label>
<input type="text" class="form-control" id="validationCustom03" placeholder="Last name" name="lastname" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom04">Father Name</label>
<input type="text" class="form-control" id="validationCustom04" placeholder="Father Name" name="fathername" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="validationCustom05">City</label>
<input type="text" class="form-control" id="validationCustom05" placeholder="City" name="city" required>
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom06">Country</label>
<input type="text" class="form-control" id="validationCustom06" value="Pakistan" name="country" required>
<div class="invalid-feedback">
Please provide a valid country.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom07">State</label>
<input type="text" class="form-control" id="validationCustom07" placeholder="State" name="state" >
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom08">Zip</label>
<input type="number" class="form-control" id="validationCustom08" value="0000" name="zip">
</div>
</div>
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="validationCustom09">Contact</label>
<input type="text" class="form-control" id="validationCustom09" placeholder="Phone Number" name="contact" required>
<div class="invalid-feedback">
Please provide a valid country.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom10">CNIC</label>
<input type="number" class="form-control" id="validationCustom10" placeholder="xxxxx-xxxxxxx-x" name="cnic" required>
<div class="invalid-feedback">
Please provide a valid country.
</div>
</div>
<div class="col-md-6 mb-3">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" placeholder="Current Address" name="address">
</div>
</div>
<div class="form-row">
<div class="file col-md-4 mb-3">
<label class="file-label" for="customFile01">Photo</label>
<input type="file" class="form-control" id="customFile01" name="photo"/>
</div>
<div class="file col-md-4 mb-3">
<label class="file-label" for="customFile02">CV</label>
<input type="file" class="form-control" id="customFile02" name="cv"/>
</div>
<div class="file col-md-4 mb-3">
<label class="file-label" for="customFile03">Other Files/Photos</label>
<input type="file" class="form-control" id="customFile03" name="otherfiles"/>
</div>
</div>
<div classs="form-row">
<button class="btn btn-primary" type="submit">Add Staff</button>
</div>
</div>
</div>
</form>
I tried my best at the above code but it gives me the error.
Error
Exception Value:
Cannot assign "'1'": "staff.staff_type" must be a "staff_type" instance.
staff_type in staff model must be staff_type model instance so first get model instance
s_type = staff_type.objects.get(id=request.POST.get('stafftype'))
staff.objects.create(...,staff_type=s_type)
Or you can also assign fk directly like this.
staff.objects.create(staff_type_id=request.POST.get('stafftype'))
And please try to follow PEP8 standards for writing python codes.
Note: It's better using django forms and Also you can use built-in generic class-based views which will make your things easier.
The problem is that you are sending number to Staff model into the field "staff_type". You either need to cast it to staff_type, or put an instance there
guys i am a beginner in programming and I desperately need your help. I am trying to develope a webapp using Django. I have created a HTML form in my index.html file. In my views.py I am trying to use the corr() fundtion of Pandas but every time it says Empty DataFrame
index.html
<form id='form' name='form' method="post" action="">
{% csrf_token %}
<div class="row">
<div class="form-group col-md-2">
<label for="Col 1">col 1</label>
<input type="text" class="form-control" id="col1" name="col1">
</div>
<div class="form-group col-md-2">
<label for="Col 2">col 2</label>
<input type="text" class="form-control" id="col2" name="col2">
</div>
</div>
<div class="row">
<div class="form-group col-md-2">
<label for="Col 3">col 3</label>
<input type="text" class="form-control" id="col3" name="col3">
</div>
<div class="form-group col-md-2">
<label for="Col 4">col 4</label>
<input type="text" class="form-control" id="col4" name="col4">
</div>
</div>
<button class="btn btn-primary" id='predict' name='predict'>Run forecast</button>
</form>
views.py
def index(request):
if request.method == "POST":
col1 = request.POST.get('col1')
col2 = request.POST.get('col2')
col3 = request.POST.get('col3')
col4 = request.POST.get('col4')
data = {'X':[col1, col2], 'Y':[col3, col4]}
df = pd.DataFrame(data)
x = df.corr()
print(x)
return render(request, 'corelation.html')
else:
return render(request,'index.html')
Every time I run this code it returns Empty DataFrame in terminal. However if I replace col1, col2 with actual numbers it shows the desired result.
First check that those GET variables are not empty or not numbers.
Then try to use the float cast method like float(col1)
This is my view.So I want to keep 2 different HTML forms in same view ,But I am unable to do so beacuse whenever I add 1 form , I get the error of other on being none.
def home(request):
name = None
if request.method == 'POST':
name = request.POST.get('name')
choices = request.POST.get('choices')
subtest = request.POST.get('subtest')
reference = request.POST.get('reference')
unit = request.POST.get('unit')
test = Test()
test.name = name
test.save()
subtest = Subtest()
subtest.test = Test.objects.get(name=choices)
subtest.name = subtest
subtest.unit = unit
subtest.reference_value = reference
subtest.save()
# print(name)
return redirect('home')
return render(request,'main.html',{})
I have got 2 different forms . I didn't use django forms because I wanted to try something new.
MY FIRST FORM
<form method="POST">
{% csrf_token %}
<div class="icon-holder">
<i data-modal-target="test-popup" class="icon-cross"></i>
</div>
<div class="input-group">
<input type="text" name="name" placeholder="Test name" />
</div>
<div class="button-group">
<button type="submit">Submit</button>
</div>
</form>
MY SECOND FORM
<form method="POST">
{% csrf_token %}
<div class="icon-holder">
<i data-modal-target="menu-test-popup" class="icon-cross"></i>
</div>
<div class="input-group">
<label for="test-select">Test Name:</label>
<select name="choices" id="test-select">
{% for test in test %}
<option value="{{test.name}}" name='choices'>{{test.name|title}}</option>
{% endfor %}
</select>
</div>
<div class="input-group">
<input type="text" name="subtest" placeholder="SubTest name" />
</div>
<div class="input-group">
<input type="text" name="reference" placeholder="Reference rate" />
</div>
<div class="input-group">
<input type="text" name="unit" placeholder="Unit" />
</div>
<div class="button-group">
<button type="submit">Submit</button>
</div>
</form>
first form
<form method="POST">
...
<input name="form_type" value="first-form" type="hidden">
</form>
second form
<form method="POST">
...
<input name="form_type" value="second-form" type="hidden">
</form>
view function
def view(request):
if method == "POST":
form_type = request.POST.get('form_type')
if form_type == "first-form":
# first form's process
elif form_type == "second-form":
#second form's process
You have two forms here, when you submit the second form, only the fields from the second form gets submitted.
so from this line
name = request.POST.get('name')
name will become None. But I believe your Test model does not take any None value for name field( the reason for you " IntegrityError at / NOT NULL constraint failed: lab_test.name ").
To overcome this, first check if there is any value for 'name' then proceed with creating the test instance
if name:
test = Test()
test.name = name
test.save()
Similarly check if the other fields are present for the second form before creating and saving the instance.
I'm using Python Pyramid with Jinja2 template. I want to save my form data into session and retrieve it in another HTML page. How should I change in order to pass the data? I only know how to store the data I key in Views.py into session like this request.session['postal'] = 01934 but this is not the data I key in Delivery.jinja2. And if I used print (session['postal']), this will only show in my command prompt but not HTML page. Can anyone help me out? I'm a beginner to this.
What to add in/ change in my Views.py?
my HTML: Delivery.jinja2
<form class="form-horizontal" method="POST">
<div class="form-group">
<label class="control-label col-md-2" for="postal">Postal Code:</label>
<input type="text" class="form-control" id="postal" placeholder="Enter Postal Code" name="postal" />
</div>
<div class="form-group">
<label class="control-label col-md-2" for="address">Detailed Address:</label>
<textarea class="form-control" rows="3" id="address" placeholder="Enter Address" name="address"></textarea>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="unit">Unit No #:</label>
<input type="text" class="form-control" id="unit" placeholder="Enter Unit No" name="unit" />
</div>
<button type="submit" class="btn btn-default" name="submit">Submit</button>
</form>
Views.py
#view_config(route_name='deliveryLink', renderer='templates/deliveryLink.jinja2')
def deliveryLink(request):
print("YAY for gift delivery via Link")
if 'submit_deliverylink' in request.POST:
print("request.POST: ", request.POST)
myform = request.POST
for m in myform:
print("key: ", m, " value: ", myform[m])
session = request.session
session['postal'] = ?
session['address'] = ?
session['unit'] = ?
data = "??"
data_array = data.split(",")
session['data'] = data_array
session['delivery'] = str(data_array)
print (session['delivery'])
return HTTPFound(location='http://localhost:5555/confirmation')
return {}
#view_config(route_name='confirmation', renderer='templates/confirmation.jinja2')
def confirmation(request):
print("YAY for confirmation")
for a in request.POST:
request.session[a] = request.POST[a]
return {}
and I want the data entered previously to show on this confirmation page: Confirmation.jinja2
<form class="form-horizontal" method="POST">
<div class="form-group">
<label class="control-label col-md-2" for="postal">Postal Code:</label>
<input type="text" class="form-control" id="postal" name="postal" />
</div>
<div class="form-group">
<label class="control-label col-md-2" for="address">Detailed Address:</label>
<textarea class="form-control" rows="3" id="address" name="address"></textarea>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="unit">Unit No #:</label>
<input type="text" class="form-control" id="unit" name="unit" />
</div>
</form>
I think, you can just pass POST from initial form to template of confirmation page, without session.
If anyway you need session, you can call it from your template
<input type="text" class="form-control" id="postal" name="postal" value="{{session['postal']}}" />
# after form submitted, it sends post request, just check if it exist
if request.POST:
print("request.POST: ", request.POST)
myform = request.POST
# you need iterate over keys for this case
for m in myform.keys():
print("key: ", m, " value: ", myform[m])
session = request.session
# you can access request.POST directly or use your variable myfrom
# use myform.get('postal','') to get value by key
session['postal'] = myform.get('postal','')
session['address'] = myform.get('postal','')
session['unit'] = myform.get('unit','')
data = "??"
data_array = data.split(",")
session['data'] = data_array
session['delivery'] = str(data_array)
print (session['delivery'])
return HTTPFound(location='http://localhost:5555/confirmation')
so no matter what I seem to do I can't get a valid form from just a integer field.
Controller:
def upload_image(request):
if request.method == "POST":
form = AddFloorplan(request.POST, request.FILES)
print request.POST.get('floornumber')
if form.is_valid():
print 'valid'
else:
print(form.errors)
return redirect("/wayfinder/editor/")
Form:
class AddFloorplan(forms.Form):
floor_number = forms.IntegerField(required=True)
Template:
<form action="/wayfinder/addfloorplan/" method="POST" enctype="multipart/form-data"> {% csrf_token %}
<div class="input-field col s12">
<input id="floornumber" autofocus name="floornumber" placeholder="Floor Number" type="text" required>
</div>
<div class="col s12">
<p>
<button class="btn waves-effect waves-light z-depth-0" type="submit" name="action">
<span>Upload</span>
</button>
</p>
</div>
</form>
had no luck passing the values
The name of your form field, floor_number
floor_number = forms.IntegerField(required=True)
does not match the name of your form input, floornumber
<input id="floornumber" autofocus name="floornumber" placeholder="Floor Number" type="text" required>
You need to use the same name in both places.