here i am using python3 and Django 3.0
Here am i saving the signature into my database and now i need to display this signature in my pdf file
But i am not able to display it in the pdf file
here is my views.py
def jobspecific_view_1(request, pk):
form = CustomerSignatureForm(request.POST or None)
if form.is_valid():
customer_signature_1 =
form.cleaned_data.get('customer_signature_1')
if customer_signature_1!=None:
job = AddJob.objects.get(id=pk)
job.customer_signature_1 = customer_signature_1
job.save()
......
......
here is my views.py for generating the pdf
def render_to_pdf(template_src, context_dict, pdf_title):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result,
encoding='UTF-8')
if not pdf.err:
response = HttpResponse(result.getvalue(), content_type='application/pdf')
response['Content-Disposition'] = "attachment; filename={0}".format(
unidecode(
pdf_title.replace(
',', '').replace(
';', '').replace(' ', '_')))
logger.debug('Content-Disposition: {0}'.format(response['Content-Disposition']))
return response
logger.error(pdf.err)
return HttpResponse('We had some errors<pre>%s</pre>' % cgi.escape(html))
def generate_pdf_view(request, pk):
client = request.user.client
job_id = AddJob.objects.filter(id=pk)
viewed_job = get_object_or_404(AddJob, id=pk, created_by__client=client)
job_data={}
for val in job_id:
job_data['job_id'] = pk
job_data['title'] = val.title
job_data['job_number'] = val.job_number
job_data['customer_signature_1'] = val.customer_signature_1
......
......
pdf_title = u'{0}_{1}_{2}.pdf'.format(
job_data['title'], job_date.strftime('%d_%m_%Y'),
job_data['job_type'])
return render_to_pdf('jobs/jobpdf.html',
{
'pagesize':'A4', 'job_data': job_data,
'viewed_job': viewed_job,
'request': request,
}, pdf_title)
Here is my forms.py
class CustomerSignForm(forms.ModelForm):
customer_signature_1 = SignatureField(required=False,label="Customer Signature")
class Meta:
model = AddJob
fields = ['customer_signature_1']
Here is my jobspdf.html
<img src="data:image/png;base64,{{job_data.custmer_signature_1}}"/>
Please help me so that i can display the signature in my pdf view at present it not displaying anything in my pdf
Related
I'm trying to create a form to enable users to add blog posts with images using flask and I saved the name of the picture in the database using SQLAlchemy like this "<FileStorage: 'IMG_20210415_114702.jpg' ('image/jpeg')>" as the name of the picture instead of this 'IMG_20210415_114702.jpg'. Please how do I correct this?
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255))
content = db.Column(db.Text)
author = db.Column(db.String(255))
date_posted = db.Column(db.DateTime, default=datetime.utcnow)
slug = db.Column(db.String(255))
poster_id = db.Column(db.Integer, db.ForeignKey("users.id"))
post_pic = db.Column(db.String(200), nullable=True)
#app.route("/add-post", methods=["GET", "POST"])
##login_required
def add_post():
form = PostForm()
if form.validate_on_submit():
poster = current_user.id
post = Post(title=form.title.data, content=form.content.data, poster_id=poster, slug=form.slug.data, post_pic=form.post_pic.data)
form.title.data = ''
form.content.data = ''
#form.author.data = ''
form.slug.data = ''
name = ''
form.post_pic.data = request.files['post_pic']
name = form.post_pic.data.filename
filepath = os.path.join(app.config['UPLOAD_FOLDER'], name)
form.post_pic.data.save(filepath)
#postpic_filename = secure_filename(form.post_pic.data.filename)
#postpic_name = str(uuid.uuid1()) + "_" + postpic_filename
#saver = request.files['post_pic']
#form.post_pic.data = postpic_name
db.session.add(post)
db.session.commit()
#saver.save(os.path.join(app.config['UPLOAD_FOLDER'], postpic_name))
flash("post submitted successfully!")
return render_template("add_post.html", form=form)
What could possibly be the course of this exception UnboundLocalError at /group/share/42/ when i try sharing post of another user in a group.The exception trace seems to be on the the first line of the forloop ( new = new_post.video.add(img) ) Here is my view for users to share post
def share_post(request, pk):
original_post = Post.objects.get(pk=pk)
form = ShareForm(request.POST)
if form.is_valid():
new_post = Post(
shared_body = request.POST.get('description'),
description = original_post.description,
username = original_post.username,
date_posted = original_post.date_posted,
shared_on = timezone.now(),
shared_user = request.user)
new_post.save()
for img in original_post.video:
shared = new_post.video.add(img)
shared.save()
return redirect('group:main',original_post.group.pk)
Here is my model Post.
new_post will only be assigned a value if the form is valid, so you should indent the for loop:
def share_post(request, pk):
original_post = Post.objects.get(pk=pk)
form = ShareForm(request.POST)
if form.is_valid():
new_post = Post(
shared_body = request.POST.get('description'),
description = original_post.description,
username = original_post.username,
date_posted = original_post.date_posted,
shared_on = timezone.now(),
shared_user = request.user
)
new_post.save()
for img in original_post.video:
new_post.video.add(img)
return redirect('group:main',original_post.group.pk)
I am trying to take image input from user in Django first the code was working fine but when I tried to run this code after a week it is giving me an attribute error and I don't why it is happening I tried to search on the internet but they only say it is because of the wrong syntax. The line, where the error arises, is file_type = file_type.lower() and line will be at last in the product_details function
views.py
from django.shortcuts import render
from django.http import HttpResponse
from datetime import datetime
from machine_website.models import contact_detail
from machine_website.models import product_data
from machine_website.forms import product_Form
# Create your views here.
def homepage(request):
descp1 = product_data()
descp1.disc = ' this is the discription'
descp1.img = '2.jpg'
descp2 = product_data()
descp2.disc = ' this is the discription 2'
descp2.img = '2.jpg'
descp3 = product_data()
descp3.disc = ' this is the discription 3'
descp3.img = '5.jpg'
descp = [descp1, descp2,descp3]
return render(request,'homepage.html', {'descp': descp})
def contact(request):
if request.method=="POST":
name = request.POST.get('name')
email = request.POST.get('email')
desc = request.POST.get('desc')
contact = contact_detail(name=name , email=email, desc=desc, date=datetime.today())
contact.save()
return render(request,'contact.html')
def services(request):
return render(request,'services.html')
def index(request):
return HttpResponse("this is index page")
def more(request):
info = product_data.objects.all()
return render(request ,'more.html' , {'info' : info})
IMAGE_FILE_TYPES = ['png' , 'PNG' , 'jpg' , 'JPG' , 'jpeg' , 'jfif']
def product_details(request):
form = product_Form()
if request.method == 'POST':
form = product_Form(request.POST, request.FILES)
if form.is_valid():
user_pr = form.save(commit=False)
user_pr.img = request.FILES['img']
file_type = user_pr.img.url.split('.')
file_type = file_type.lower()
if file_type not in IMAGE_FILE_TYPES:
return render(request, 'error.html')
user_pr.save()
return render(request, 'details.html', {'user_pr': user_pr})
context = {"form": form,}
return render(request, 'product_details.html', context)
TRACEBACk CALL
File "C:\Users\naveen\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\naveen\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\naveen\Desktop\cpp programs\first django project\machine_website\views.py", line 59, in product_details
file_type = file_type.lower()
AttributeError: 'list' object has no attribute 'lower'
[17/Apr/2021 17:00:46] "POST /product_details/ HTTP/1.1" 500 67315
I am new to python. I am trying to send a response showing a custom keyboard with two buttons to the user in Telegram app but it gives me an error about encode.
I would like to know where is my mistake.
import json
from urllib.request import urlopen
from urllib.parse import quote, unquote
import time
def Decode(telegram_response):
decoded=''
for line in telegram_response:
decoded=decoded+line.decode('utf-8')
return decoded
TOKEN = 'mytoken'
URL = 'https://api.telegram.org/bot{}/'.format(TOKEN)
cmd = 'getme'
telegram_response = urlopen(URL + cmd)
decoded = Decode(telegram_response)
gtm = json.loads(decoded)
status = True
while status:
cmd = 'getUpdates'
telegram_response = urlopen(URL + cmd)
decoded = Decode(telegram_response)
upds = json.loads(decoded)
new_message = len(upds['result'])
if new_message !=0:
msg = upds['result'][0]['message']
chat_id = str(msg['chat']['id'])
reply_markup = {'keyboard': [[{'text':'first button'}],[{'text':'second button'}]], 'resize_keyboard': True, 'one_time_keyboard': True}
reply_markup = json.dumps(reply_markup)
params = ({'chat_id': chat_id, 'reply_markup': reply_markup, 'disable_web_page_preview': 'true'})
myresponse =urlopen(URL + 'sendMessage' + quote((params).encode('utf-8')))
Easy way to build powerful bots is to use python-telegram-bot library.
I re-writed your code with few major fixes and features. Hope it help you to learn bots more deeper.
my version of bot:
###############################################################################
!#/usr/bin/python3
from sys import exc_info as error
from urllib.request import urlopen
from urllib.parse import urlencode
import json
TOKEN = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'
URL = 'https://api.telegram.org/bot{}'.format(TOKEN)
STATUS = True
OFFSET = 0
def call_api_method(method='getMe', data=None):
# Call API method with data.
data = urlencode(data).encode("utf-8") if data else data
response = urlopen('{}/{}'.format(URL, method), data)
return json.loads(response.read())
def get_me():
# Get bot info.
bot = call_api_method()
return type('Bot', (), dict(bot['result']))
def get_updates():
# Get new updates from Telegram.
data = {'offset': OFFSET, 'limit': 0, 'timeout': 0}
return type('Updates', (), call_api_method('getUpdates', data))
def handle(update):
# Make usefull objects.
message = type('Message', (object,), dict(update['message']))
user = type('User', (), dict(update['message']['from']))
chat = type('Chat', (), dict(update['message']['chat']))
return message, user, chat
def send_message(chat_id, message):
# Send message to specific chat.
data = {'text': message,
'chat_id': chat_id,
'parse_mode': 'Markdown',
'disable_web_page_preview': True}
call_api_method('sendMessage', data)
def send_keyboard(chat_id, message, keyboard):
# Send message and keyboard to specific chat.
data = {'text': message,
'chat_id': chat_id,
'parse_mode': 'Markdown',
'reply_markup': reply_markup(keyboard),
'disable_web_page_preview': 'true'}
call_api_method('sendMessage', data)
def reply_markup(keyboard):
# Serialize keyboard data to JSON.
return json.dumps({'keyboard': keyboard,
'resize_keyboard': True,
'one_time_keyboard': True,
'selective': True})
def main_keyboard():
# Main menu.
return [first_button(), second_button()]
def one_line_keyboard():
# Menu with buttons in one line.
return [two_buttons()]
def first_button():
# Single keyboard button.
return ['first button']
def second_button():
# Single keyboard button.
return ['second button']
def two_buttons():
# Two buttons on one line.
return ['left button', 'right button']
while STATUS:
# Get updates forever. Except if get Error.
try:
if not OFFSET:
OFFSET = 1
# Print bot info on the start.
bot = get_me()
print('Bot #{} is running...'.format(bot.username))
updates = get_updates()
for update in updates.result:
# Handle last update.
OFFSET = update['update_id'] + 1
message, user, chat = handle(update)
# Greeting user by full name.
greeting = 'Hello, {} {}!'.format(user.first_name, user.last_name)
#send_message(chat.id, greeting)
send_keyboard(chat.id, greeting, one_line_keyboard())
except:
STATUS = False
print('\nERROR:\t', error()[1])
###############################################################################
you can this code: I hope useful for you .
i change :
params = ({'chat_id': chat_id, 'reply_markup': reply_markup, 'disable_web_page_preview': 'true'})
myresponse =urlopen(URL + 'sendMessage' + quote((params).encode('utf-8')))
with:
params = ({'text': 'ss', 'chat_id': chat_id, 'reply_markup': reply_markup, 'disable_web_page_preview': 'true'})
data = urllib.parse.urlencode(params).encode("utf-8")
myresponse = urlopen(URL + 'sendMessage', data)
complate code :
import json
import urllib
from urllib.parse import quote
from urllib.request import urlopen
def Decode(telegram_response):
decoded = ''
for line in telegram_response:
decoded = decoded + line.decode('utf-8')
return decoded
TOKEN = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'
URL = 'https://api.telegram.org/bot{}/'.format(TOKEN)
cmd = 'getme'
telegram_response = urlopen(URL + cmd)
decoded = Decode(telegram_response)
gtm = json.loads(decoded)
status = True
while status:
cmd = 'getUpdates'
telegram_response = urlopen(URL + cmd)
decoded = Decode(telegram_response)
upds = json.loads(decoded)
new_message = len(upds['result'])
if new_message != 0:
msg = upds['result'][0]['message']
chat_id = str(msg['chat']['id'])
reply_markup = {'keyboard': [[{'text': 'first button'}], [{'text': 'second button'}]], 'resize_keyboard': True,
'one_time_keyboard': True}
reply_markup = json.dumps(reply_markup)
params = ({'text': 'ss', 'chat_id': chat_id, 'reply_markup': reply_markup, 'disable_web_page_preview': 'true'})
data = urllib.parse.urlencode(params).encode("utf-8")
myresponse = urlopen(URL + 'sendMessage', data)
I want upload a file with a Groovy script to Confluence.
As this Pythonscript example!
I started to translate the code into groovy,
// Groovy
def server = new XMLRPCServerProxy("http://confluence:8090/rpc/xmlrpc")
def spaceKey = "Area"
def pageTitel = "FileUpload"
def contentType = "application/pdf"
def token = server.confluence2.login("UserName","Password")
def page = server.confluence2.getPage(token, spaceKey, pageTitel)
def fileName = "D:\\datamodel.pdf"
def file = new File (fileName)
//
//Up to this point it works!!!
but i found nothing in groovy for the last steps!
//Python Script from Examplelink above
//.....
attachment = {};
attachment['fileName'] = os.path.basename(filename);
attachment['contentType'] = contentType;
server.confluence1.addAttachment(token, page['id'], attachment, xmlrpclib.Binary(data));
I think, i must have an object for the attachments and a method to store the attachment on the given page in the server.
FINAL WORKING CODE
def server = new XMLRPCServerProxy("http://confluence:8090/rpc/xmlrpc")
def spaceKey = "Area"
def pageTitel = "FileUpload"
def fileName = "D:\\datamodel.pdf"
def contentType = "application/pdf"
def token = server.confluence2.login("UserName" , "Password")
def page = server.confluence2.getPage(token, spaceKey, pageTitel)
def file = new File (fileName)
server.confluence2.addAttachment( token, page.id, [ fileName: file.name, contentType:contentType ], file.bytes )
Looking at the docs, it looks like you should be able to do:
server.confluence2.addAttachment( token,
page.id,
[ fileName: file.name,
contentType:'application/pdf' ],
file.bytes )