How to save image, generated by qrcode, Django? - django

How to load image to bd, well i generate qr image(QRcode)when she is generated, i need to create a new record in bd, to save this image and code himslef
This is my model
class QRCode(models.Model):
user = models.ForeignKey(UserProfile, blank=True, default=None)
qr_code = models.CharField(max_length=120)
qr_code_img = models.ImageField(upload_to="qr_code_img/", width_field="width_field", height_field="height_field")
upcoming_show = models.ForeignKey(SectionUpcomingShow)
width_field = models.IntegerField(default=270)
height_field = models.IntegerField(default=270)
is_active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return "{0} - - {1}".format(self.user.username, self.is_active)
class Meta:
ordering = ["-timestamp"]
verbose_name = 'QRCode'
verbose_name_plural = 'QRCodes'
#property
def image_path(self):
return os.path.abspath(self.qr_code_img)
this is view to gen qrimg
def qr_code_generator(hex_code, username, __show__id, __show__name__, __show__q, price):
qr_code_generate_himslef = pyqrcode.create(hex_code)
generate_name = ''.join(username + '_' + str(__show__id) + '_' + __show__name__ + '_' + str(__show__q) + '_' + str(price) + '.png').replace(" ", "_")
qr_code_generate_himslef.png(generate_name, scale=6)
print(qr_code_generate_himslef)
return qr_code_generate_himslef
when i print this function i got this
QRCode(content=b'f40a03cb6026d68f0f83c43b47c9e388ed106848', error='H', version=5, mode='binary')
this is my save view
new_qr_code, created = QRCode.objects.get_or_create(user=get_user_profile, qr_code=hex_code, is_active=True, defaults={"user":get_user_profile, "qr_code":hex_code, "qr_code_img":qr_img, "upcoming_show":get_upcoming_show})
if not created:
pass

when you run this function
def qr_code_generator(hex_code, username, __show__id, __show__name__, __show__q, price):
qr_code_generate_himslef = pyqrcode.create(hex_code)
generate_name = ''.join(username + '_' + str(__show__id) + '_' + __show__name__ + '_' + str(__show__q) + '_' + str(price) + '.png').replace(" ", "_")
qr_code_generate_himslef.png(generate_name, scale=6)
print(qr_code_generate_himslef)
return qr_code_generate_himslef
the qr_code image file will be produced in your root directory(the directory having your manage.py file) with the name 'generate_name' variables value.
then open that image like
import os
from django.core.files import File
with open(generate_name, 'rb') as qr_img:
new_qr_code, created = QRCode.objects.get_or_create(user=get_user_profile, qr_code=hex_code, is_active=True, defaults={"user":get_user_profile, "qr_code":hex_code, "qr_code_img":File(qr_img), "upcoming_show":get_upcoming_show})
if not created:
pass
and your qr_image will be uploaded to your 'upload_to' location given in models field. you can put this code in try block to avoid exceptions.
you can then remove the useless qr code image generated by that function
os.remove(generate_name)
hope it helps...

Related

Saving many-to-many fields from the excel file in Django

I'm trying to save the student data from an excel file. I'm reading the excel file row-wise and mapping the data to the model fields. Now the problem is that there is a foreign key and a many-to-many field which I don't know how to save. Though I figured out the foreign key part but not able to solve the second part.
Here are the files.
views.py
def fileUpload(request):
if request.method=="POST":
form= UserDataUploadView(request.POST, request.FILES)
try:
excel_file= request.FILES["excel_file"]
except MultiValueDictKeyError: # In case the user uploads nothing
return redirect('failure_page')
# Checking the extension of the file
if str(excel_file).endswith('.xls'):
data= xls_get(excel_file, column_limit=10)
elif str(excel_file).endswith('.xlsx'):
data= xlsx_get(excel_file, column_limit=10)
else:
return redirect('failure_page')
studentData= data["Sheet1"]
print("Real Data", studentData)
# reading the sheet row-wise
a_list= studentData
list_iterator= iter(a_list)
next(list_iterator)
for detail in list_iterator:
# To find out empty cells
for data in detail:
if data==" ":
print('A field is empty')
return redirect('user_upload')
print("DATA: ", detail)
user=User.objects.create(
firstName = detail[6],
lastName = detail[7],
password = detail[8],
username = detail[9],
)
# instance=user.save(commit=false)
# Student.batch.add(detail[0])
student=Student.objects.create(
user = user,
email = detail[1],
rs_id = detail[2],
dob = detail[3],
address = detail[4],
age = detail[5],
)
student.save()
return render(request, 'classroom/admin/success_page.html', {'excel_data':studentData})
# iterating over the rows and
# getting value from each cell in row
# for row in worksheet.iter_rows():
# row_data= list()
# for cell in row:
# row_data.append(str(cell.value))
# excel_data.append(row_data)
# return render(request, 'classroom/admin/excel.html', {'excel_data':excel_data})
else:
form=UserDataUploadView()
return render(request, 'classroom/admin/fill_users.html', {
'form':form,
# 'excel_data':excel_data,
})
models.py
class Subject(models.Model):
school = models.CharField(max_length=50, null=True)
name = models.CharField(max_length=30)
color = models.CharField(max_length=7, default='#007bff')
def __str__(self):
return self.name
def get_html_badge(self):
name = escape(self.name)
color = escape(self.color)
html = '<span class="badge badge-primary" style="background-color: %s">%s</span>' % (color, name)
return mark_safe(html)
class Batch(models.Model):
name = models.CharField(max_length=30, unique=True)
school = models.CharField(max_length=50)
amount_of_fees = models.IntegerField(null=True)
subjects = models.ManyToManyField(Subject)
#property
def students(self):
return self.student_set.all()
def __str__(self):
return self.name
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, default=None)
batch = models.ManyToManyField(Batch)
email = models.EmailField(null=True)
phone_number = models.CharField(max_length=10, null=True)
dob = models.DateField(blank=True, null=True, help_text="Enter in the following format : YYYY-MM-DD")
address = models.TextField(max_length=150, null=True)
age = models.IntegerField(blank=True)
image = models.ImageField(upload_to='profile_pictures', default='student_image.png', blank=True)
rs_id = models.IntegerField(blank=True,default=0)
I don't know how to put the data for batch in the excel sheet. Kindly give insight for that too.
Assuming detail[0] is the name field for the Batch model, you would do:
student_batch = Batch.objects.get(name=detail[0])
student=Student.objects.create(
user = user,
email = detail[1],
rs_id = detail[2],
dob = detail[3],
address = detail[4],
age = detail[5],
)
student.batch.add(student_batch)
student.save()
You will also need to update your Batch field on the Student model to:
batch = models.ManyToManyField(Batch, blank=True)

My pre_save signal isn't applying my string generator

I wrote a simple string generator for my order_id field.
I tested the generator script in shell, and it works perfectly.
But when I run the server, and try to create an order in django admin, the order id field remains empty when I click save.
What am I doing wrong?
from datetime import date
from django.db import models
from django.db.models.signals import pre_save
from cartapp.models import Cart
class Order(models.Model):
order_id = models.CharField(max_length=120)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
status = models.CharField(max_length=50, default='Waiting', null=True, blank=True)
order_total = models.DecimalField(default=0.0, max_digits=10, decimal_places=1)
date_created = models.DateTimeField(auto_now_add=True)
def order_id_generator(instance):
today = date.today().strftime("%Y-%m-%d")
last_order_raw = Order.objects.latest('order_id').date_created
last_order_date = str(last_order_raw).split(' ')[0]
if today != last_order_date:
new_order_id = str(today + " 1")
else:
last_order = Order.objects.latest('order_id')
extract = last_order.order_id.split(' ')[1]
increment = int(extract) + 1
new_order_id = today + " " + str(increment)
return new_order_id
def pre_save_order_id(sender, instance, *args, **kwargs):
if not instance.order_id:
instance.order_id = order_id_generator(instance)
pre_save.connect(pre_save_order_id, sender=Order)
I noticed that you are passing instance to order_id_generator but doesn't use it there. You can avoid using signals and you can use your function as the model field default:
class Order(models.Model):
order_id = models.CharField(max_length=120, default=order_id_generator)
and you doesn't need an arg instance in your function:
def order_id_generator():
today = date.today().strftime("%Y-%m-%d")
last_order_raw = Order.objects.latest('order_id').date_created
last_order_date = str(last_order_raw).split(' ')[0]
if today != last_order_date:
new_order_id = str(today + " 1")
else:
last_order = Order.objects.latest('order_id')
extract = last_order.order_id.split(' ')[1]
increment = int(extract) + 1
new_order_id = today + " " + str(increment)
return new_order_id

How do i specify a file upload in django to a folder in reference to one of the model fields

I have the following django models in my Document app
class Section(models.Model):
choices = (
('Haematology', 'Haematology'),
('BloodBank', 'BloodBank'),
('Bacteriology', 'Bacteriology'),
('Parasitoloty', 'Parasitoloty'),
('Chemistry', 'Chemistry'),
('Histopathology', 'Histopathology'),
('Serology', 'Serology'),
('Immunology', 'Immunology'),
)
title = models.CharField(max_length = 50, choices = choices)
class Meta:
verbose_name = "Section"
verbose_name_plural = "Sections"
def __str__(self):
return str(self.title)
class Document(models.Model, instance):
documentSection = models.ForeignKey(Section)
category = models.ForeignKey(DocumentCategory)
title = models.CharField(max_length = 100, default = '')
description = models.TextField(null = True, blank = True, default = '')
documentFile = models.FileField(upload_to = 'uploads/' + instance.documentSection.title)
fileFormat = models.ForeignKey(FileFormat)
uploaded = models.DateField(auto_now_add=True, default=timezone.now)
modified = models.DateTimeField(auto_now=True, default=timezone.now)
uploaded_by = models.ForeignKey(User)
def __str__(self):
return str(self.title)
When i upload Documents i want then to be saved in a folder like 'uploads/documentSection/
or 'uploads/documentSection/%Y/%m/
My problem is i cant figure out how to take the value of the documentSection and parse it to upload_to = 'uploads/documentSection/

Django: Aggregate and Sum with a join with another table without the forign key constraint

Here is my models.py file.
from django.db import models
from django.contrib.auth.models import User
class image(models.Model):
name = models.CharField(max_length = 200)
src = models.URLField()
alt = models.CharField(max_length = 200)
points = models.IntegerField(default = 0)
id = models.CharField(max_length = 200, primary_key = True)
hotelId = models.IntegerField()
def __unicode__(self):
return self.name
class imagescore(models.Model):
user = models.ForeignKey(User)
image_id = models.CharField(max_length = 200)
score = models.IntegerField(default = 1)
createdTime = models.DateTimeField(auto_now_add =True)
def __unicode__(self):
if self.score < 0:
status = " rejected "
else:
status = "approved"
return (self.user+ status+ image_id)
pass
I would like to pass on to my template a table that is a result of the SQL Query:
select ei.id,ei.src, ei.hotelId , sum(score)
from eyeballing_image ei LEFT join eyeballing_imagescore eis on ei.id = eis.image_id
where user_id = request.user.id and ei.hotelId = 56565
group by
ei.id,ei.src, ei.hotelId
My app name is eyeballing. O tried using joins and filters bot i couldn't make it work.
Additionally, i tried making the sum(score) part into a separate dict and check the same in the template. Didn't work
Any help will be appreciated.
Your query has two problems, one in column name hotelId. you must use it in query in this way ei."hotelId".
Other problem is in condition user_id = request.user.id because you have not request in sql and you must replace it with a value.
Maybe another problem is in return (self.user + status + image_id) that must be return (self.user + self.status + self.image_id).

Postal Code model field shows up as State list in Admin

Not sure, but I think this may be a bug?
Here is my model:
class Property(models.Model):
Name = models.CharField(max_length=40)
Description = models.TextField(default="Description Not Available")
Address = models.CharField(max_length=60, default="Not Available")
Address2 = models.CharField(max_length=60,null=True)
City = models.CharField(max_length=60, null=True)
State = usa_model.USStateField(null=True)
Code = usa_model.USPostalCodeField(null=True)
Phone = usa_model.PhoneNumberField(null=True)
Am I missing something?
-Kerry
Perhaps you are looking for the US Zip Code Form Field?
The USPostalCodeField uses a list of the states + a few extras:
COFA_STATES = (
('FM', 'Federated States of Micronesia'),
('MH', 'Marshall Islands'),
('PW', 'Palau'),
)
At django.contrib.localflavor.us.us_states
# USStateField
STATE_CHOICES = tuple(sorted(US_STATES + US_TERRITORIES + ARMED_FORCES_STATES, key=lambda obj: obj[1]))
# USPostalCodeField
USPS_CHOICES = tuple(sorted(US_STATES + US_TERRITORIES + ARMED_FORCES_STATES + COFA_STATES, key=lambda obj: obj[1]))