**I want to fetch information from course titile & course code textbox ,,,, if title & code both are given or only title /code data will be showed.
Bt, in my code not working when only title are given..
what are the logical mistake..?? My View Code
def search_view(request):
c = 0
d = 0
c_title = ''
c_code = ''
course_Details = ''
course_Details1 = ''
if request.GET.get('Code'):
c_code = request.GET.get("Code")
if request.GET.get('Course_Title'):
c_title = request.GET.get("Course_Title")
if c_code != '':
course_Details = Course.objects.filter(course_code=c_code)
if (course_Details):
c = 1
if c_title != '':
if c == 1:
course_Details1 = course_Details.filter(course_title=c_title)
if (course_Details1):
d = 1
if d == 1:
course_Details = course_Details1
if d == 0:
course_Details = Course.objects.filter(course_title=c_title)
if c == 1 | d == 1:
return render(request, 'index.html', {'course_Details': course_Details})
else:
return render(request, 'index.html')
You need to set d=1 when you query by title only:
def search_view(request):
c = 0
d = 0
c_title = ''
c_code = ''
course_Details = ''
course_Details1 = ''
if request.GET.get('Code'):
c_code = request.GET.get("Code")
if request.GET.get('Course_Title'):
c_title = request.GET.get("Course_Title")
if c_code != '':
course_Details = Course.objects.filter(course_code=c_code)
if (course_Details):
c = 1
if c_title != '':
if c == 1:
course_Details1 = course_Details.filter(course_title=c_title)
if (course_Details1):
d = 1
if d == 1:
course_Details = course_Details1
if d == 0:
course_Details = Course.objects.filter(course_title=c_title)
d = 1
if c == 1 | d == 1:
return render(request, 'index.html', {'course_Details': course_Details})
else:
return render(request, 'index.html')
Related
Please, can anyone help me out. I am trying to call a function I defined in my views.py under food_app into another application in my project. after calling it, it works but I have a problem in reading out the function objects on my html template. it usually displays "₦<HttpResponse status_code=200, "text/html; charset=utf-8">"
But the objects prints out on the terminal after when printed.
This is the first function defined
views.py #food_app
def price_in_packs(request):
total_price1 = ""
total_price2 = ""
total_price3 = ""
total_price4 = ""
total_price5 = ""
total_price6 = ""
total_price7 = ""
total_price8 = ""
total_price9 = ""
total_price10 = ""
total_price11 = ""
total_price12 = ""
price_pack_box1 = ""
price_pack_box2 = ""
price_pack_box3 = ""
price_pack_box4 = ""
price_pack_box5 = ""
price_pack_box6 = ""
price_pack_box7 = ""
price_pack_box8 = ""
price_pack_box9 = ""
price_pack_box10 = ""
price_pack_box11 = ""
price_pack_box12 = ""
food = ""
food_price = ""
#try and except is used here to avoid a null or empty value input by the user. A user can forget to input a price in pack value, which can break the code.
if request.method == "POST":
if request.POST["form"] == "form1":
try:
price_pack_box1 = int(request.POST.get("price1"))
food = Food.objects.get(pk=1)
food_price = food.food_price
total_price1 = price_pack_box1*food_price
print(total_price1)
except ValueError:
return render(request,'food_app/404.html')
elif request.POST["form"] == "form2":
try:
price_pack_box2 = int(request.POST.get("price2"))
food = Food.objects.get(pk=2)
food_price = food.food_price
total_price2 = price_pack_box2*food_price
print(total_price2)
except ValueError:
return render(request,'food_app/404.html')
elif request.POST["form"] == "form3":
try:
price_pack_box3 = int(request.POST.get("price3"))
food = Food.objects.get(pk=3)
food_price = food.food_price
total_price3 = price_pack_box3*food_price
print(total_price3)
except ValueError:
return render(request,'food_app/404.html')
elif request.POST["form"] == "form4":
try:
price_pack_box4 = int(request.POST.get("price4"))
food = Food.objects.get(pk=4)
food_price = food.food_price
total_price4 = price_pack_box4*food_price
print(total_price4)
except ValueError:
return render(request,'food_app/404.html')
elif request.POST["form"] == "form5":
try:
price_pack_box5 = int(request.POST.get("price5"))
food = Food.objects.get(pk=5)
food_price = food.food_price
total_price5 = price_pack_box5*food_price
print(total_price5)
except ValueError:
return render(request,'food_app/404.html')
elif request.POST["form"] == "form6":
try:
price_pack_box6 = int(request.POST.get("price6"))
food = Food.objects.get(pk=6)
food_price = food.food_price
total_price6 = price_pack_box6*food_price
print(total_price6)
except ValueError:
return render(request,'food_app/404.html')
elif request.POST["form"] == "form7":
try:
price_pack_box7 = int(request.POST.get("price7"))
food = Food.objects.get(pk=7)
food_price = food.food_price
total_price7 = price_pack_box7*food_price
print(total_price7)
except ValueError:
return render(request,'food_app/404.html')
elif request.POST["form"] == "form8":
try:
price_pack_box8 = int(request.POST.get("price8"))
food = Food.objects.get(pk=8)
food_price = food.food_price
total_price8 = price_pack_box8*food_price
print(total_price8)
except ValueError:
return render(request,'food_app/404.html')
elif request.POST["form"] == "form9":
try:
price_pack_box9 = int(request.POST.get("price9"))
food = Food.objects.get(pk=9)
food_price = food.food_price
total_price9 = price_pack_box9*food_price
print(total_price9)
except ValueError:
return render(request,'food_app/404.html')
elif request.POST["form"] == "form10":
try:
price_pack_box10 = int(request.POST.get("price10"))
food = Food.objects.get(pk=10)
food_price = food.food_price
total_price10 = price_pack_box10*food_price
print(total_price10)
except ValueError:
return render(request,'food_app/404.html')
elif request.POST["form"] == "form11":
try:
price_pack_box11 = int(request.POST.get("price11"))
food = Food.objects.get(pk=11)
food_price = food.food_price
total_price11 = price_pack_box11*food_price
print(total_price11)
except ValueError:
return render(request,'food_app/404.html')
elif request.POST["form"] == "form12":
try:
price_pack_box12 = int(request.POST.get("price12"))
food = Food.objects.get(pk=12)
food_price = food.food_price
total_price12 = price_pack_box12*food_price
print(total_price12)
except ValueError:
return render(request,'food_app/404.html')
#Total price represents the nummber of the number input of price in packs
#while price_in_pack_box is the amount of the amount of the product in packs
my_dict = {'new_price1':[total_price1,price_pack_box1],'new_price2':[total_price2,price_pack_box2],
'new_price3':[total_price3,price_pack_box3],'new_price4':[total_price4,price_pack_box4],
'new_price5':[total_price5,price_pack_box5],'new_price6':[total_price6,price_pack_box6],
'new_price7':[total_price7,price_pack_box7],'new_price8':[total_price8,price_pack_box8],
'new_price9':[total_price9,price_pack_box9],'new_price10':[total_price10,price_pack_box10],
'new_price11':[total_price11,price_pack_box11],'new_price12':[total_price12,price_pack_box12]}
return render(request, 'food_app/price.html',context=my_dict)
I need to use the price_in_packs function in this view
views.py #payment app
def payment(request, pk):
item = ""
if request.method == "POST":
if request.POST.get("form") == "form1":
seerbit_pay = request.POST.get("ewa")
return render(request,'payments/pay.html',{'pk':pk,'all_pk':all_pk,'soup':soup_box,'price_in_pack':packs(request)})
After calling the price_in_pack key in my template view, it displace this "₦<HttpResponse status_code=200, "text/html; charset=utf-8">" but I want it to display the object instead.
**QPainter::begin(): Returned false============================] 100%
Error: Unable to write to destination
Exit with code 1, due to unknown error.**
def view_entry_pdf(request,id):
standard_fields = ['user_username','user_email', 'form_id', 'entry_id', 'date_dmy','user_full_name']
try:
entry = Entries.objects.get(pk=id)
cert = Certificate.objects.filter(form_id=entry.form.id, is_active=1).first()
get_cert = request.GET.get('cert_id','')
if get_cert:
cert = Certificate.objects.get(id=get_cert)
if not cert:
messages.warning(request, 'PDF template not found.')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
valid_rules = validate_rules(entry,cert, cert.rules.all())
if valid_rules:
pass
else:
messages.warning(request, 'Certificate rules not matched.')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
entry.is_read = True
entry.save()
file_name = 'entry-certificate.pdf'
if cert.file_name:
file_name = cert.file_name
res = re.findall(r'(\{\{[^}]+}\})', file_name)
placeholders = {}
standard_placeholders = {}
#standard_fields
for sf in standard_fields:
sfv = ''
if sf == 'user_username':
sfv = entry.user.username
elif sf == 'user_email':
sfv = entry.user.email
elif sf == 'form_id':
sfv = str(entry.form.id)
elif sf == 'entry_id':
sfv = str(entry.id)
elif sf == 'date_dmy':
today = datetime.now().date()
sfv = today.strftime("%d-%m-%Y")
elif sf == 'user_full_name':
sfv = f"{entry.user.first_name} {entry.user.last_name}"
standard_placeholders['{{'+sf+'}}'] = sfv
standard_placeholders = account_placeholders(request, standard_placeholders)
if res:
fields_all = entry.form.fields.all().order_by('sort_order')
for f in fields_all:
key = '{{'+f.label_name.replace(" ", "_").lower()+'}}'
placeholders[key] = f.id
for p in res:
f_id = placeholders.get(p)
if p and f_id:
en_data = entry.columns.filter(field_id=f_id)
val = ''
if en_data.count() and en_data[0].value:
val = en_data[0].value
file_name = file_name.replace(p, val)
elif standard_placeholders.get(p):
file_name = file_name.replace(p, standard_placeholders[p])
cert_path = '{}/form/certificates/{}'.format(settings.MEDIA_ROOT,file_name)
#cert_path = 'media/form/certificates/{file_name}'
url = '{}://{}/admin/forms/entry-pdf/{}?system_run=1&cert={}'.format(request.scheme, request.get_host(), entry.id, cert.id)
print("reached here------------------------------")
options = {
'dpi': 365,
'page-size':cert.page_type,
'orientation':cert.orientation
}
pdfkit.from_url(url,cert_path,options=options)
#set pdf permissions
setPdfPermissions(cert, cert_path)
return FileResponse(open(cert_path, 'rb'), content_type='application/pdf')
except FileNotFoundError:
raise Http404()
I am converting html to pdf. This code worked fine before. I dont know what kind of problem is arrising now. I am not aware of this tool htmltopdf. If i am doing anything wrong please help me
Here is a picture of the import file that is to be imported
I want to read the course column but when I exclude the group column, it shows all the columns are being skipped. How can I import this file?
This is the code currently:
class courseAttendanceResource(resources.ModelResource):
Student_ID = Field(attribute='Student_ID', column_name='Student ID')
Username = Field(attribute='Username', column_name='Username')
ID_number = Field(attribute='ID_number', column_name='ID number')
Institution = Field(attribute='Institution', column_name='Institution')
Department = Field(attribute='Department', column_name='Department')
Surname = Field(attribute='Surname', column_name='Surname')
First_name = Field(attribute='First_name', column_name='First name')
Groups = Field(attribute='Groups', column_name='Groups')
P = Field(attribute='P', column_name='P')
L = Field(attribute='L', column_name='L')
E = Field(attribute='E', column_name='E')
A = Field(attribute='A', column_name='A')
Taken_sessions = Field(attribute='Taken_sessions', column_name='Taken sessions')
Points = Field(attribute='Points', column_name='Points')
Percentage = Field(attribute='Percentage', column_name='Percentage')
def get_export_headers(self):
headers = super().get_export_headers()
for i, h in enumerate(headers):
if h == 'Student ID':
headers[i] = 'Student_ID'
if h == 'Username':
headers[i] = 'Username'
if h == 'ID number':
headers[i] = 'ID_number'
if h == 'Institution':
headers[i] = 'Institution'
if h == 'Department':
headers[i] = 'Department'
if h == 'Surname':
headers[i] = 'Surname'
if h == 'First name':
headers[i] = 'First_name'
if h == 'Groups':
headers[i] = 'Groups'
if h == 'P':
headers[i] = 'P'
if h == 'L':
headers[i] = 'L'
if h == 'E':
headers[i] = 'E'
if h == 'A':
headers[i] = 'A'
if h == 'Taken sessions':
headers[i] = 'Taken_sessions'
if h == 'Points':
headers[i] = 'Points'
if h == 'Percentage':
headers[i] = 'Percentage'
return headers
class Meta:
model = courseAttendance
with open('/tmp/rows.csv') as csvfile:
# skip the first 3 lines
[next(csvfile, None) for i in range(3)]
# now load the dataset
ds = tablib.Dataset()
ds.csv = csvfile.read()
print(ds)
dataset = ds
result = resource.import_data(dataset)
import_id_fields = ('Student_ID',)
exclude = ('Course', 'Group',)
fields = ('Student_ID', 'Username', 'ID_number', 'Institution', 'Department', 'Surname', 'First_name', 'Groups',
'P', 'L', 'E', 'A', 'Taken_sessions', 'Points', 'Percentage',)
#export_order = ('Student_ID', 'Username', 'ID_number', 'Institution', 'Department', 'Surname','First_name', 'Groups', 'P', 'L', 'E', 'A','Taken_sessions', 'Points', 'Percentage')
skip_unchanged = True
report_skipped = True
I need to read the course and exclude the group column. After that i want to read the rest of the columns. I applied your answer but it gives me an error at
result = resource.import_data(dataset)
Create a Dataset before you call import_data():
Given a csv file:
Course
Group
Student ID,Username
123,abc
import tablib
with open('/tmp/rows.csv') as csvfile:
# skip the first 3 lines
[next(csvfile, None) for i in range(3)]
# now load the dataset
ds = tablib.Dataset()
ds.csv = csvfile.read()
print(ds)
Produces:
Student ID|Username
----------|--------
123 |abc
Once you have loaded your dataset, you can call the import_data() method:
result = resource.import_data(dataset)
Is there a way to save the current time + 1 hour or 1day or 1week to a DatetimeField using django view orm?
for example
models.py
dead_line = models.DateTimeField(blank=True, default=utc_tomorrow)
def add_todo_by_ajax(request):
title = request.POST['title']
dead_line_option = request.POST['dead_line_option']
# print("dead_line_option : " , dead_line_option)
if dead_line_option == "1h":
print ("1h")
# deadline =
elif (dead_line_option == "4h"):
print ("4h")
elif (dead_line_option == "8h"):
print ("8h")
elif (dead_line_option == "1d"):
print ("1d")
elif (dead_line_option == "8h"):
print ("1w")
todo = Todo.objects.create(title=title, author=request.user, director = request.user)
print("todo(insert result) : " , todo)
user_update = Profile.objects.filter(user=request.user.id).update(uncompletecount = F('uncompletecount')+1)
return HttpResponse(redirect('/todo/'))
this is answer that I find
if dead_line_option == "1h":
print ("1h")
dead_line = datetime.now() + timedelta(hours=1)
elif (dead_line_option == "4h"):
print ("4h")
dead_line = datetime.now() + timedelta(hours=4)
elif (dead_line_option == "8h"):
print ("8h")
dead_line = datetime.now() + timedelta(hours=8)
elif (dead_line_option == "1d"):
print ("1d")
dead_line = datetime.now() + timedelta(hours=24)
elif (dead_line_option == "1w"):
print ("1w")
dead_line = datetime.now() + timedelta(days=7)
I'm getting the incorrect output of a query set when I use request.method == 'POST' and selectedaccesslevel == '#' showing as <QuerySet ['S00009']> when it's written to the database.
I believe I should be using a get since i'm expecting one value, but how do I filter my get on coid = owner.coid.coid and provide the value ?level?
I'm looking for my output for datareducecode to be 'S00009' and not <QuerySet ['S00009']>. How can I accomplish this? Below is my view...
def submitted(request):
owner = User.objects.get (formattedusername=request.user.formattedusername)
checkedlist = request.POST.getlist('report_id')
print (f"checkedlist on submitted:{checkedlist}")
access_request_date = timezone.now()
coid = User.objects.filter(coid = request.user.coid.coid).filter(formattedusername=request.user.formattedusername)
datareducecode = OrgLevel.objects.distinct().filter(coid=request.user.coid.coid)
# facilitycfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True)
# divisioncfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True)
# print(facilitycfo)
# print(divisioncfo)
selectedaccesslevel = request.POST.get('accesslevelid')
print (f"accesslevel:{selectedaccesslevel}")
selectedphi = request.POST.get('phi')
print (f"phi:{selectedphi}")
print (owner.coid.coid)
if request.method == 'POST' and selectedaccesslevel == '3':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('slevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '4':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('blevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '5':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('rlevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '6':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('dlevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '7':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('f"Z{Coid}"', flat = True)
print (datareducecode)
else:
datareducecode = 'No Match on Coid'
print (datareducecode)
for i in checkedlist:
requestsave = QVFormAccessRequest(ntname = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid.coid, facility = owner.facility, title = owner.title
,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi , access_beg_date = access_request_date, datareducecode = datareducecode )
requestsave.save()
# print (datareducecode)
return JsonResponse({'is_success':True})
So this seems to do the trick:
list(datareducecode)[0]