pass an image from views to html template without saving - django

in this code I tried to write on an image that is in the computer and i take a name from the user to write on the image and display it
but i want to pass it to an html template without save in the database or in the disk
here i use a FileResponse
How could I pass it through render to an Html template
this is the method in my Views.py
def app(request):
if request.method == "POST":
res = resultImages()
name = request.POST.get('name')
reshaped_text = arabic_reshaper.reshape(name)
bidi_text = get_display(reshaped_text)
my_image = Image.open("static/images/firstTest.jpeg")
#title_font = ImageFont.load_default()
font = ImageFont.truetype("arial.ttf", size=32)
title_text = bidi_text
image_editable = ImageDraw.Draw(my_image)
res.img=image_editable.text((248, 537), title_text, fill="red" ,font = font)
timeNow = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
filename = "%s%s.jpg" % (timeNow, name)
res.name = name
my_image.save(filename)
res.save()
im = open(filename,'rb')
return FileResponse(im)
return render(request,'img.html')

Related

inserting a lot of data via create_bulk

hello I have a table named Exercise data where I pass data from form and save them in the db, my problem is that I have more same objects to save inside the db but I don't know how to do it.
I left you my views.py file where you can find the code I created.
I read around that I should use the create_bulk but I don't understand how I can pass it some data from my form, could someone help me please? =)
views.py
#login_required
def creaScheda(request):
if request.method == "POST":
form = CreaSchedaForm(request.POST)
if form.is_valid():
schedaName = form.cleaned_data['nome_scheda']
scheda = form.save(commit = False)
scheda.utente = request.user
scheda.save()
gruppi = DatiGruppi(
giorni_settimana = form.cleaned_data['giorni_settimana'],
dati_gruppo = form.cleaned_data['dati_gruppo'],
gruppi_scheda = Schede.objects.get(nome_scheda = schedaName)
)
gruppi.save()
esercizi = DatiEsercizi(
serie = form.cleaned_data['serie'],
ripetizione = form.cleaned_data['ripetizione'],
peso = form.cleaned_data['peso'],
gruppo_single = DatiGruppi.objects.get(gruppi_scheda = scheda.id),
dati_esercizio = form.cleaned_data['dati_esercizio']
)
#esercizi.save()
print(esercizi)
return redirect('/backoffice')
else:
form = CreaSchedaForm()
context = {"form": form}
return render(request, "crea_scheda.html", context)

How to upload a file from django view using filepath

I have to upload a file from django views using the file path from the local system. I'm using models.create method to save the filepath. But the image is not getting uploaded into the media directory.
I have tried the Content and File from django core.utils but it deos not work
def createevent(request):
file_path = os.path.join(settings.FILES_DIR) # Getting the directory with files
f = []
for (dirpath, dirnames, filenames) in walk(file_path):
f.extend(filenames)
break
f.remove(".DS_Store")
img = random.choice(f) # Select a random file
pa = os.path.abspath(img) # absolute file path
# pa = (img,File(pa))
response = File(pa)
print(pa)
loc = "School Ground"
if request.method == 'POST':
get_dateof = request.POST.get('dateof')
get_nameof = request.POST.get('nameof')
get_descof = request.POST.get('descof')
new_report = Event.objects.create(
name=get_nameof,
description=get_descof,
location=loc,
timeoftheevent=get_dateof,
user=request.user,
image= pa
) #creating a db record
return HttpResponse('')
my models.py
class Event(models.Model):
name = models.CharField(max_length=100,blank=False)
description = models.CharField(max_length=100,blank=False)
location = models.CharField(max_length=100,blank=False)
timeoftheevent = models.CharField(max_length=100,blank=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
image = models.FileField(blank=False)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.username
You can try this.
#This would return a path for your saved images using path name/filename you can always tweak this
def user_directory_path(instance,filename):
return '{0}/{1}'.format(instance.name, filename)
class Event(models.Model):
name = models.CharField(max_length=100,blank=False)
description = models.CharField(max_length=100,blank=False)
location = models.CharField(max_length=100,blank=False)
timeoftheevent = models.CharField(max_length=100,blank=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
image = models.FileField(upload_to = user_directory_path, blank=False)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.username
then in your views.py and I'm assuming myfile is the name of the file field in your html form
if request.method == 'POST' and and request.FILES['myfile']:
get_dateof = request.POST.get('dateof')
get_nameof = request.POST.get('nameof')
get_descof = request.POST.get('descof')
myfile = request.FILES['myfile']
#creating a db record............
return HttpResponse('')
you can have a look at this article if it helps

Django: I need to open a file in one view that I created in another view [duplicate]

I'm having the worst time with this one. In a view I created a csv file that's saved to memory. I need to get that csv file to a utils.py function and post to an external api. I for the life of me can not figure out how to do this and it's really driving me nuts.
I originally was just trying to create it in the run_test_suite_in_hatit function below and then somehow open it in the run_all_modal below but that wasn't working. What occurred below was the file (hatit_csv_filename) was now a message object. I don't want to save it to a model as its temporary and is being created purely to be sent right in a api post within HATScript() which is in a utils.py file within the same app in the my project. I'm not sure how to get the file to HATScript() which is just making me nuts.
def run_test_suite_in_hatit(request):
testrail_suite_id = int(request.GET['suite'])
print(testrail_suite_id)
testrail_instance = TestRailInstance.objects.first()
project = request.user.humanresource.project
testrail_project_id = project.testrail.project_id
testrail_project = get_testrail_project(testrail_instance, testrail_project_id)
testrail_suites = testrail_project.get_suites()
testrail_suite = [s for s in testrail_suites if s.id == testrail_suite_id][0]
testrail_cases = testrail_suite.get_cases()
hatit_csv_filename = bulk_hatit_file_generator(testrail_cases)
messages.add_message(request, messages.INFO, hatit_csv_filename)
return HttpResponseRedirect('/run_all_modal/')
def run_all_modal(request):
if request.method == 'POST':
form = TestRunnerForm(request.POST)
if form.is_valid():
data = form.cleaned_data
scripts = get_messages(request)
csvfile = ""
for script in scripts:
csvfile = script
hs = HATScript()
hs.apn = data.get('apn')
hs.holly_server = data.get('browser')
hs.basic_connection_test()
response = hs.hatit_execute()
else:
print(form.errors)
return JsonResponse({'success': True})
EDIT: SOLVED
I have been bashing my head over this and it was so obvious what I needed to do !
Updated View functions:
def run_test_suite_in_hatit(request):
testrail_suite_id = int(request.GET['suite'])
testrail_instance = TestRailInstance.objects.first()
project = request.user.humanresource.project
testrail_project_id = project.testrail.project_id
testrail_project = get_testrail_project(testrail_instance, testrail_project_id)
testrail_suites = testrail_project.get_suites()
testrail_suite = [s for s in testrail_suites if s.id == testrail_suite_id][0]
testrail_cases = testrail_suite.get_cases()
hatit_csv_filename = bulk_hatit_file_generator(testrail_cases)
**HATScript.csvfile = hatit_csv_filename**
return 'runner/run_all_modal.html'
def run_all_modal(request):
if request.method == 'POST':
form = TestRunnerForm(request.POST)
if form.is_valid():
data = form.cleaned_data
hs = HATScript()
**hs.csvfile = HATScript.csvfile**
hs.apn = data.get('apn')
hs.holly_server = data.get('browser')
response = hs.hatit_execute()
print(response.status_code)
else:
print(form.errors)
return redirect('runner:dashboard')
I was trying to send to a function within a class and populate the variables with the appropriate data but because the data was coming from 2 different Views I was beside myself on how to achieve this. I have tried so many ridiculous things. I removed any proprietary bits.
class HATScript(AutomationScript):
def __init__(self, apn='', body='', dialed_number='',
holly_server='', sonus_server='',
hatit_server='',
remote_server=' ', remote_user='', remote_password=''):
self.csvfile = ''
self.hatit_server = hatit_server
self.apn = apn
self.dialed_number = dialed_number
self.body = body
self.filename = ''
self.holly_server = holly_server
self.sonus_server = sonus_server
self.remote_server = remote_server
self.remote_user = remote_user
self.remote_password = remote_password
def hatit_execute(self):
"""Uses Frank's HAT User Interface to initate a HAT test"""
browser = requests.session()
stuff = browser.get('http://{0}/hatit'.format(self.remote_server))
print(stuff.status_code)
data = {'apn': self.apn,
'browser': self.holly_server,
'port': '5060'}
response = browser.post("http://{0}/".format(self.hatit_server), data=data, files={'csvfile': open(self.csvfile)})
print(response.text)
browser.close()
return response
Essentially I was able to assign the variable the file in the run_test_suite_in_hatit(request) function and had to this SO question helped me understand working with Class variables and assigning to them etc. Which helped me solve the issue I've been having for so long that I came into work on it more on a Saturday night.

django pdf with logo image

I have created Invoice Pdf text template using pisa. But I want to display logo(image) in the pdf file along with the text. I dont know how to display image in pdf. My views as follows:
def generate_invoice(request, user_id = None):
personal_html = ''
personal_html += 'hai'
fileread = str(settings.TEMPLATE_DIRS[0])+str('/invoice.html')
fr = open(fileread, "r").read()
fr = fr.replace('personal_details', personal_html)
result = StringIO.StringIO()
pdf = pisa.CreatePDF(
fr,result
)
filewrite = str(settings.TEMPLATE_DIRS[0]) + str('/invoice_write.html')
empty = ""
fw = open(filewrite, 'w')
fw.write(empty)
fw.write(fr)
fw.close()
PaymentPdf.objects.filter(invoicepdf = user_id).delete()
pdf_contents = render_to_pdf1('invoice_write.html',result)
file_to_be_saved = ContentFile(pdf_contents)
random_str = ''.join(random.sample((string.ascii_lowercase + string.ascii_uppercase + string.digits), 8))
resume_name = (str(user_id) + "_" + random_str + ".pdf").replace("#", '')
resume = PaymentPdf.objects.create(name = resume_name, invoicepdf_id = user_id, created_by = request.user)
resume.name.save(resume_name ,file_to_be_saved)
file_path = PaymentPdf.objects.get(invoicepdf = user_id).name
pdf_file = str(file_path).split("media")[1]
return HttpResponseRedirect('/site_media' + pdf_file)
def render_to_pdf1(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
return result.getvalue()
Anyone help me to display image in pdf?
Refer Pisa (XHTML -> PDF) in Django will not display images in PDF, and add the lines
links = lambda uri, rel: os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ''))
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")),dest=result, link_callback=links)
in render_to_pdf1 of views,
and in html:
<img src="/site_media/img/logo.jpg"/ height="55" width="275">
It will work.
I think that the html contain something like this:
<img src="/media/xxx.jpg"/>
And pisa need something like this:
<img src="http://mydomain.foo/media/xxx.jpg"/>

Getting Input Data from a formular and use it as a parameter for a function

Hello I wanted to know if it possible to get input-data from a formular and use this data for another function?
my forms.py:
class TextPathForm(forms.Form):
text = forms.CharField(required=True)
language = forms.CharField(required=True)
stopwords = forms.CharField(required=False)
search = forms.CharField(required=False)
filterword = forms.CharField(required=False)
my view.py:
def textpath(request):
success = False
text = ''
stopwords = ''
language = ''
search = ''
if request.method == 'POST':
textpath_form = TextPathForm(request.POST)
if textpath_form.is_valid():
success = True
text = textpath_form.cleaned_data['text']
stopwords = textpath_form.cleaned_data['stopwords']
language = textpath_form.cleaned_data['language']
search = textpath_form.cleaned_data['search']
else:
textpath_form = TextPathForm()
ctx = {'textpath_form':textpath_form,'text':text,'language':language,'stopwords':stopwords,'search':search,'succes': success,}
return render_to_response('index.html',ctx)
def any_function("need parameter text from textpath() "):
Thanks for helping me.
What do you mean? You can always pass textpath_form.cleaned_data to your function as an argument or even pass textpath_form.cleaned_data['text'] and do something with it there.