I tried to get multiple data from the checkbox using method below in my views.py:
if (((request.POST.get('data_choice ')) == ('Salary')) and ((request.POST.get('data_choice ')) and ((request.POST.get('data_choice ')) == ('Overtime')) ):
But the problem is the "and" condition is not working but if i use "or" condition it's work. May I know what's the problem with my code ? Is the request.POST.get can only get 1 data ?
choices.py
class DataChoices(models.TextChoices):
salary = 'Salary',_('Salary')
bonus = 'Bonus',_('Bonus')
allowance= 'Allowance',_('Allowance')
overtime= 'Overtime',_('Overtime')
models.py
class Data(models.Model):
Data_choices = Data_choices
data_choices = models.CharField(max_length=40,choices=Data_choices.choices,blank = True, null= True)
forms.py
class dataForm(forms.ModelForm):
datachoice = DataChoices
data_choice = forms.MultipleChoiceField(label=False,choices=datachoice .choices, required=True,widget=forms.CheckboxSelectMultiple(
attrs= {
"checked":"checked"
}))
class Meta:
model = Data
fields = ('__all__')
html
<form class="form" method="POST">
{% csrf_token %}
<fieldset class="form-group">
<h4 style="display:inline-block;" class="title-section">PRINT FORM</h4>
<div class="card">
<div class="card-body">
<div class="row col" >
<h5>Please select data to be included in the form</h5>
</div>
<div class="row mt-4">
<div class="col-lg">{{ form.data_choice |as_crispy_field }}</div>
</div>
</div>
<div class="col " style="text-align:center;">
<button class='btn btn-info btn-block'>Next</button>
</div>
</div>
</fieldset>
</form>
views.py
if form.is_valid:
data = {
'data_choice ':request.POST.get('data_choice '),
}
if (((request.POST.get('data_choice ')) == ('Salary')) and ((request.POST.get('data_choice ')) == ('Bonus')) ):
request.session['decision_data'] = data
return redirect ('printformA')
else:
messages.error(request, f'Error in creating Form')
return render(request, 'selectdata.html',context)
use QueryDict.getlist(key, default=None)
Usage:
data_choice = request.POST.getlist('data_choice')
Related
I am creating a website in which there is a form where you can book appointments(for doctors)..The issue I am facing is that, if a particular timeslot(for the particular date and time) has been selected it should not appear anymore on the form, but I have no clue on how to do it
The form looks like this(This is returned from the index function in views.py)
<section id="appointment" data-stellar-background-ratio="3">
<div class="container">
<div class="row">
<div class="col-md-6 col-sm-6">
<img src="{% static 'images/appointment-image.jpg' %}" class="img-responsive" alt="">
</div>
<div class="col-md-6 col-sm-6">
<!-- CONTACT FORM HERE -->
<form id="appointment-form" role="form" method="post" action="{% url 'test' %}">
{% csrf_token %}
<!-- SECTION TITLE -->
<div class="section-title wow fadeInUp" data-wow-delay="0.4s">
<h2>Make an appointment</h2>
</div>
<div class="wow fadeInUp" data-wow-delay="0.8s">
<div class="col-md-6 col-sm-6">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Full Name">
</div>
<div class="col-md-6 col-sm-6">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Your Email">
</div>
<div class="col-md-6 col-sm-6">
<label for="date">Select Date</label>
<input type="date" name="date" value="" class="form-control">
</div>
<div class="col-md-6 col-sm-6">
<label for="select">Select Department</label>
<select class="form-control" name="drop">
{% for entry in items %}
<option>{{ entry.category }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-6 col-sm-6">
<label for="select">Select Time</label>
<select class="form-control" name="drop1">
{% for entry in times %}
<option>{{ entry.time }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-12 col-sm-12">
<label for="telephone">Phone Number</label>
<input type="tel" class="form-control" id="phone" name="phone" placeholder="Phone">
<label for="Message">Additional Message</label>
<textarea class="form-control" rows="5" id="message" name="message" placeholder="Message"></textarea>
<button type="submit" class="form-control" id="cf-submit" name="submit">Submit Button</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
The views.py, the test function saves the form(into database) and sends the email:
from django.shortcuts import render, get_object_or_404
from django.core.mail import send_mail
from .models import Form, categories, Doctors, News, timeslot
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import authenticate
def index(request):
time = timeslot.objects.all()
item = categories.objects.all() # use filter() when you have sth to filter ;)
if request.method == 'POST':
selected_item = get_object_or_404(Item, pk=request.POST.get('item_id'))
selected_item2 = get_object_or_404(time, pk=request.POST.get('time_id'))
# get the user you want (connect for example) in the var "user"
categories.item = selected_item
categories.save()
timeslot.time = selected_item2
timeslot.save()
# Then, do a redirect for example
return render(request, 'website/index.html', {'items':item, 'times':time })
def test(request):
if request.method == "POST":
name=request.POST['name']
email=request.POST['email']
date=request.POST['date']
drop=request.POST.get('drop', False)
time=request.POST.get('drop1', False)
phone=request.POST['phone']
message1=request.POST['message']
message = "Name: "+ name + "\n" + "email: "+ email + "\n" + "Date of appointment: " + date + "\n" + "Time: " + time + "\n" "Service: " + drop + "\n" + "Number: " + phone + "\n" + "Special Message: "+ message1
#send an email
send_mail(
'Make appointment for ' + name, #subject
message, #the msg
email, #from email
['madhavm2002#gmail.com'] #to email
)
#this is used to get the class from the models and then uses the variables assigned here to give value to the variables in models
form=Form(name = name, email = email, date = date, time= time, drop = drop, phone = phone, msg1= message1)
#this used the save method to save the object into the database
form.save()
return render(request, 'website/test.html', {'name':name})
else:
return render(request, 'website/index.html')
The models.py:
from django.db import models
class Form(models.Model):
msg_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=80)
email = models.CharField(max_length=80)
date = models.DateField()
drop = models.CharField(max_length=80)
time = models.TimeField()
phone = models.CharField(max_length=80)
msg1 = models.CharField(max_length=500)
status = models.IntegerField(default = 0)
class categories(models.Model):
category = models.CharField(max_length=80)
class timeslot(models.Model):
time = models.TimeField(max_length=80)
PS: the timeslots looke like 9am,10am,11am...1pm,2pm etc.
The categories give objects like "dental","physio" etc
Do tell how to solve this issue thanks
Essentially you'll need to have something to indicate available timeslots, then with a query joined to your appointments you'd have a condition in your template that that checks if the timeslot already has an appointment (or not) and act accordingly. This is a fairly broad question - see Brian's note.
I've been working on a project lately and got the above error. It says " Error during template rendering".I have a similar model, which works perfectly fine. I've looked for similar errors but got none matching my situation. I don't know where I went wrong. It would be great if I get helpful answers.
Models.py
class ServiceTax(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="service_tax",null=True,blank=True)
name=models.CharField(max_length=100)
percent=models.FloatField(default='0')
add_amount=models.IntegerField(default='0')
def __str__(self):
return self.name
Forms.py
class ServiceTaxForm(forms.ModelForm):
class Meta:
model = ServiceTax
fields = "__all__"
widgets = {
'name' : forms.TextInput(attrs={'class': 'form-control'}),
'percent' : forms.NumberInput(attrs={'class': 'form-control','step':'0.01'}),
'add_amount' : forms.NumberInput(attrs={'class':'form-control','maxlength':5}),
}
labels={
'add_amount': "Additional Amount"
}
Views.py
def tax_form(request,id=0):
if request.method == 'GET':
if id == 0:
form = ServiceTaxForm(request)
else:
tax = ServiceTax.objects.get(pk=id)
if tax in request.user.service_tax.all():
form = ServiceTaxForm(request,instance=tax)
else:
return redirect('/revenue/tax')
return render(request,'tax-form.html',{'form':form})
else:
if id==0:
form = ServiceTaxForm(request,request.POST)
if form.is_valid():
name = form.cleaned_data["name"]
percent = form.cleaned_data["percent"]
add_amount = form.cleaned_data["add_amount"]
t = AnnualTax(
name=name,
percent=percent,
add_amount=add_amount,
)
t.save()
request.user.service_tax.add(t)
else:
tax = ServiceTax.objects.get(pk=id)
if tax in request.user.service_tax.all():
form = ServiceTaxForm(request,request.POST,instance=tax)
if form.is_valid():
name = form.cleaned_data["name"]
percent = form.cleaned_data["percent"]
add_amount = form.cleaned_data["add_amount"]
tax_obj = ServiceTax.objects.get(pk=id)
tax_obj.name = name
tax_obj.percent = percent
tax_obj.add_amount = add_amount
tax_obj.save()
return redirect('/revenue/tax')
tax-form.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<i class="fa fa-chevron-circle-left fa-3x m-2"></i>
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header">
<h4 class="card-title">Add Service Tax</h4>
</div>
<div class="card-body">
<form action="" method="POST" autocomplete="off">
{% csrf_token %}
<div class="row">
<div class="col-md-4 pr-1">
<div class="form-group">
{{ form.name | as_crispy_field}}
</div>
</div>
<div class="col-md-4 pr-1">
<div class="form-group">
{{ form.percent | as_crispy_field}}
</div>
</div>
<div class="col-md-4 pr-1">
<div class="form-group">
{{ form.add_amount | as_crispy_field}}
</div>
</div>
</div>
<button type="submit" class="btn btn-success btn-fill pull-right">
{% if request.get_full_path == '/income/tax/add/' %}
Add Tax
{% else %}
Update
{% endif %}
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
You should retrieve your forms passing request.METHOD, not just request
As an example this piece of code form = ServiceTaxForm(request) should be form = ServiceTaxForm(request.POST)
I am trying to create multiple forms in one template page(dischargedetails.html) using different views. Each form model is having foreignkey Ipd,First form (ProcedureForm) is working fine but the in Second form(investigation Form) not able to display investigation date feild and investigation name field
models.py :
class Investigation(models.Model):
id = models.AutoField(primary_key = True)
ipd = models.ForeignKey(Ipd,on_delete = models.DO_NOTHING)
name = models.CharField(max_length=60)
report = models.TextField(max_length=500)
date = models.DateField(("Date"), default=datetime.date.today)
class Procedure(models.Model):
id = models.AutoField(primary_key = True)
ipd = models.ForeignKey(Ipd,on_delete = models.DO_NOTHING)
report = models.TextField(max_length=500)
date = models.DateField(("Date"), default=datetime.date.today)
time = models.TimeField( blank=True,default=now)
urls.py :
re_path(r'^(?P<ipd_id>\d+)/dischargedetails/$', my_patient.discharge_detail, name='discharge_details'),
views.py:
#login_required
def discharge_detail(request,ipd_id):
object = get_object_or_404(Ipd,pk=ipd_id)
if request.method =="POST":
procedure = ProcedureForm(request.POST)
if procedure.is_valid():
procedure.save()
return HttpResponseRedirect(request.path_info)
else :
return HttpResponse(procedure.errors.as_data())
else :
prolist=Procedure.objects.all().filter(ipd=ipd_id)
procedure = ProcedureForm()
return render(request, 'dischargedetails.html',{'object':object,'procedure':procedure,'prolist':prolist})
if request.method=="POST":
investigation = InvestigationForm(request.POST)
if investigation.is_valid():
inves = investigation.save(commit = False)
inves.object = object
inves.save()
return HttpResponseRedirect(request.path_info)
else:
return HttpResponse(investigation.errors.as_data())
else :
investigationlist = Investigation.objects.all().filter(ipd=ipd_id)
investigation = InvestigationForm()
return render(request, 'dischargedetails.html',{'object':object,'investi':investigation,'investilist':investigationlist})
#login_required
def create_investigation(request,ipd_id):
object = get_object_or_404(Ipd,pk=ipd_id)
template
<form method="post" action="{% url 'discharge_detail' ipd_id=object.ipd_id %}" enctype="multipart/form-data">
<label>Date</label>
<div class="input-group date">
{{ investi.date| add_class:'form-control' }}
<label id="addNotesIDhelp" class="error" for=""></label>
</div>
<div class="form-group">
<textarea id="notesTextId" name = "report" type="text" placeholder="Add Investigation"class="form-control" value = "{{investi.report}}" required></textarea>
<div class="form-group">{{investi.name | add_class:'form-control'}} <label>Report Name</label></div>
</div>
{% for pro in investilist %}
<div class="media">
<div class="shadow w-100 p-3 mb-5 bg-white rounded">
<div class="media-body" style="background-color: rgb(173, 181, 212)">
<h4 class="media-heading">{{pro.name}}{{pro.date}}</h4>
<br>
<p style="color: black">{{pro.report}}</p>
<br>
</div>
</div>
</div>
{% endfor %}
I have a Django project and I encountered with a problem of comparing a database foreign key attribute with form foreign key attribute. My project files are below :
My Model.py File:
class Teacher(models.Model):
Name = models.CharField(max_length=100)
Designation = models.CharField(max_length=100,choices=DESIGNATION)
Department = models.CharField(max_length=100,choices=T_Dept)
Address = models.CharField(max_length=100)
def __str__(self):
return self.Name + ", " + self.Designation + ", " + "("+self.Department +"), "+ self.Address
class Moderation(models.Model):
year = models.CharField(max_length=100,choices=T_Year)
semester = models.CharField(max_length=100,choices=T_Semester)
examtype = models.CharField(max_length=30,choices=EXAMTYPE)
examyear = models.CharField(max_length=30,choices=EXAMYEAR)
NamAdd = models.ForeignKey(Teacher, on_delete=models.CASCADE)
position = models.CharField(max_length=100,choices=POSITON)
def __str__(self):
return unicode(self.NamAdd)
My forms.py File :
class modaForm(forms.ModelForm):
class Meta:
model=Moderation
fields=[
'year',
'semester',
'NamAdd',
'position','examtype','examyear'
]
My HTML File :
<form action="{% url 'modIni' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="col-sm-12 col-md-4">
<br>
<div class="input-group">
<span class="input-group-addon">Year </span>
{% load widget_tweaks %}
{{ modForm.year|add_class:"form-control" }}
</div>
</div>
<div class="col-sm-12 col-md-4">
<br>
<div class="input-group">
<span class="input-group-addon">Semester </span>
{% load widget_tweaks %}
{{ modForm.semester|add_class:"form-control" }}
</div>
</div>
<div class="col-sm-12 col-md-4">
<br>
<div class="input-group">
<span class="input-group-addon">Exam Type</span>
{% load widget_tweaks %}
{{ modForm.examtype|add_class:"form-control" }}
</div>
</div>
<div class="col-sm-12 col-md-4">
<br>
<div class="input-group">
<span class="input-group-addon">Exam Year</span>
{% load widget_tweaks %}
{{ modForm.examyear|add_class:"form-control" }}
</div>
</div>
<div class="col-sm-12 col-md-4">
<br>
<div class="input-group">
<span class="input-group-addon">Name and Address</span>
{% load widget_tweaks %}
{{ modForm.NamAdd|add_class:"form-control" }}
</div>
</div>
<div class="col-sm-12 col-md-4">
<br>
<div class="input-group">
<span class="input-group-addon">Position </span>
{% load widget_tweaks %}
{{ modForm.position|add_class:"form-control" }}
</div>
</div>
<div class="col-sm-12 col-md-12">
<br>
<center>
<button type="submit" class="btn btn-success btn-lg"><spam class="glyphicon glyphicon-send"> </spam> Submit</button>
</center>
</div>
</form>
My View.py File :
def modIni(request):
modForm = modaForm(request.POST or None,request.FILES or None)
year = modForm['year'].value()
semester = modForm['semester'].value()
examtype = modForm['examtype'].value()
examyear = modForm['examyear'].value()
NamAdd = modForm['NamAdd'].value()
position = modForm['position'].value()
fMod = Moderation.objects.all().last
if modForm.is_valid():
instance = modForm.save(commit=False)
flag =True
for obj in Moderation.objects.all():
if obj.year == year and obj.semester == semester and obj.examtype == examtype and obj.examyear == examyear and obj.NamAdd == NamAdd and obj.position == position:
context = {'fMod':fMod,'modForm':modForm,'msg':"<span style='color:red;'><h3>Already Inserted!</h3> Last entry : </span>"}
flag = False
break
if flag:
instance.save()
#modForm = modaForm()
context = {'NamAdd':NamAdd,'fMod':fMod,'modForm':modForm,'msg':"<span style='color:#4BB543;'><h3>successfully accomplished!</h3> Last entry : </span>"}
else:
context = {'fMod':fMod,'modForm':modForm,'msg':"<span style='color:Red;'> <center>Please fill in all the fields</center>Last entry : </span>"}
return render(request, 'tbs/form/modaration.html',context)
How to compare obj.NamAdd.Name == NamAdd in view File? Please help me by providing any hint.
Basically, I want to save a unique Moderation object into database How doing this? Has any alternative way?
Thanks advance.
Whats wrong with obj.NamAdd == NamAdd ?
Many.
The primary issue for the comparison failure is that NamAdd is an integer(Teacher object id) where obj.NamAdd is a model object.
So, on this regard, it should be obj.NamAdd.id == NamAdd
Don't do this please. Not that way. You are bypassing input validation.
It could be obj.NamAdd == modForm.cleaned_data['NamAdd']
Since you want unique Moderation,
add this to the model:
class Meta:
unique_together = (('year', 'semester', 'examtype', 'examyear', 'NamAdd', 'position'))
so that it now looks like
class Moderation(models.Model):
year = models.CharField(max_length=100, choices=[])
semester = models.CharField(max_length=100, choices=[])
examtype = models.CharField(max_length=30, choices=[])
examyear = models.CharField(max_length=30, choices=[])
NamAdd = models.ForeignKey(Teacher, on_delete=models.CASCADE)
position = models.CharField(max_length=100, choices=[])
def __str__(self):
return unicode(self.NamAdd)
class Meta:
unique_together = (('year', 'semester', 'examtype', 'examyear', 'NamAdd', 'position'))
(remember makemigrations and migrate)
**note I used empty list for choices, adjust for your case.
now in the view, use this for checking moderation existence:
moderation_exists = Moderation.objects.filter(year=modForm.cleaned_data['year'], semester=modForm.cleaned_data['semester'],examtype=modForm.cleaned_data['examtype'], examyear=modForm.cleaned_data['examyear'], NamAdd=modForm.cleaned_data['NamAdd'], position=modForm.cleaned_data['position']).exists()
if moderation_exists:
context = {'fMod': fMod, 'modForm': modForm,
'msg': "<span style='color:red;'><h3>Already Inserted!</h3> Last entry : </span>"}
flag = False
When I submit my form from webpage, I am not able to commit. Flashing data I need, I see they're there and correct, but something fails when committing. I am sure I am making a mistake somewhere because mostly commit are working except two. This is one of the two that is not working.
Models:
class Feedback(db.Model):
__tablename__ = 'feedback'
id = db.Column(db.Integer, primary_key = True)
rate = db.Column(db.Integer)
comment = db.Column(db.Text())
sender_id = db.Column(db.Integer)
receiver_id = db.Column(db.Integer)
Forms:
class LeaveFeedbackForm(Form):
rate = IntegerField('Rate', validators = [DataRequired(),
NumberRange(min = 1, max = 5, message = 'Rates admitted are only 1,2,3,4,5')])
comment = TextAreaField('Comment', validators = [DataRequired()])
submit = SubmitField('Submit')
Views:
#app.route('/leave_feedback/<sender>/<receiver>', methods = ['GET', 'POST'])
def leave_feedback(receiver, sender):
form = LeaveFeedbackForm()
rec = int(receiver)
sen = int(sender)
if form.validate_on_submit():
feedback = Feedback( rate = form.rate.data,
comment = form.comment.data,
receiver_id = rec,
sender_id = sen
)
db.session.add(feedback)
db.session.commit()
flash('Feedback Left Correctly.')
return redirect(url_for('index'))
flash(form.rate.data)
flash(form.comment.data)
flash(rec)
flash(sen)
return render_template('leave_feedback.html', receiver_id = receiver, sender_id = sender, form = form)
html:
{% block content %}
<div class="row">
<div class="large-6 columns">
<h1>Leave Feedback</h1>
</div>
</div>
<form action="" method="post" name="leavefeedback">
<div class="row">
<div class="large-6 columns">
<label>Rate
{{ form.rate }}
</label>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<label>Comment
{{ form.comment }}
</label>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<input class="button radius" type="submit" value="Leave Feedback">
</div>
</div>
</form>
{% endblock %}
You should add an else statement:
if form.validate_on_submit():
...
else:
for error in form.errors.itervalues():
flash(error[0])
Then you will get an error message from form.
I figured out my mistake, I simply forgot in my form:
{{ form.hidden_tag() }}