here is my model in django :
import os
def upload_location_buy(instance, filename):
ext = filename.split('.')[-1]
filename = '%s.%s' % (instance.name+"_"+str(random.randint(1000, 9999)), ext)
print(os.path.join('uploads', filename))
return os.path.join('uploads', filename)
class Buy(models.Model):
pic_front = models.ImageField(blank=True, upload_to=upload_location_buy,default='')
When i try :
b = Buy(pic_front="appartement_a.jpg")
b.save()
it does nothing exception linking the current pic in the current path, so not using the function in the model.
And when i do :
b = Buy(pic_front=upload_location_buy("appartement_a.jpg"))
b.save()
it give me an error because it seems to need the instance.
TypeError: upload_location_buy() missing 1 required positional
argument: 'filename'
How to create a buy object, giving it a picture and using the upload_location_buy whend doing it without the admin ?
When i upload a pic in the admin it works.
how to give it the instance name or do it correctly ?
this is this script :
import sys
import os
import django
from django.core.exceptions import ObjectDoesNotExist
sys.path.append("../../../testproject")
os.environ["DJANGO_SETTINGS_MODULE"] = "testproject.settings"
django.setup()
from on_plan.models import Buy
Buy.objects.all().delete()
b = Buy(pic_front=upload_location_buy("appartement_a.jpg"))
b.save()
The script is in the same directory as the file "appartement_a.jpg".
-on_plan/
-testproject/
-import_script.py
-appartement_a.jpg
-manage.py
if i do a :
file_to_save = open('appartement_a.jpg', 'r').read()
b = Buy(pic_front=file_to_save)
b.save()
i have a:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
if i do a :
file_to_save = open('appartement_a.jpg', 'rb').read()
b = Buy(pic_front=file_to_save)
b.save()
i have a:
AttributeError: 'bytes' object has no attribute '_committed'
the solution is here:
import requests
import urllib.parse
import sys
import os
import django
import csv
import time
import random
from django.core.exceptions import ObjectDoesNotExist
sys.path.append("../../../sample_estate")
os.environ["DJANGO_SETTINGS_MODULE"] = "sample_estate.settings"
django.setup()
from django.core.files.base import File
from on_plan.models import Buy
file_to_save = open('appartement_a.jpg', 'rb')
b = Buy(pic_front=File(file_to_save))
b.save()
When you create a Buy object you need to pass file-obejct into pic_front attribute, but you try to pass only name of file.
from django.core.files.base import File
file_to_save = open('/path/to/appartement_a.jpg', 'r').read()
b = Buy(pic_front=File(file_to_save))
b.save()
If you get file from a form you may upload it like that:
b = Buy(pic_front=request.FILES['file'])
b.save()
Anyway pic_front expect to getting a file-object not string
More about this case
Related
I am working with SQLAlchemy and Flask-Admin right now. Let us say that I am trying to get a String of the file name or a String of the absolute path of the file name of an image file. I am trying to insert either of these into a database automatically when I create a user. The code that I am using is structured similar to this.
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
url_pic = Column(String(50), nullable=False)
pic = Column(LargeBinary, nullable=False)
...
from flask.ext.admin.contrib.sqla import ModelView
from flask.ext.admin.form.upload import FileUploadField
from wtforms.validators import ValidationError
from flask.ext.admin import Admin
from flask.ext.sqlalchemy import SQLAlchemy
from flask import Flask
import imghdr
app = Flask(__name__)
db = SQLAlchemy(app)
class UserAdminView(ModelView):
def picture_validation(form, field):
if field.data:
filename = field.data.filename
if filename[-4:] != '.jpg':
raise ValidationError('file must be .jpg')
if imghdr.what(field.data) != 'jpeg':
raise ValidationError('file must be a valid jpeg image.')
field.data = field.data.stream.read()
return True
form_columns = ['id','url_pic', 'pic']
column_labels = dict(id='ID', url_pic="Picture's URL", pic='Picture')
def pic_formatter(view, context, model, name):
return 'NULL' if len(getattr(model, name)) == 0 else 'a picture'
column_formatters = dict(pic=pic_formatter)
form_overrides = dict(pic= FileUploadField)
form_args = dict(pic=dict(validators=[picture_validation]))
admin = Admin(app)
admin.add_view(UserAdminView(User, db.session, category='Database Administration'))
...
How could we get a string version of the file name or absolute path when using the picture_validation function? Right now, the function only provides the binary data of the file, which isn’t as useful.
After writing the following code and expecting the output to be an updated database with random names, websites, etc., I get no error message and no updated database
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'First_project.settings')
import django
django.setup()
import random
from first_app.models import AccessRecord,Webpage,Topic
from faker import Faker
fakegen = Faker()
topics = ['Search','Social','Marketplace','News','Games']
def add_topic():
t = Topic.object.get_or_create(top_name=random.choice(topics))[0]
t.save()
return t
def populate(N=5):
for entry in range(N):
top = add_topic()
fake_url = fakegen.url()
fake_date = fakegen.date()
fake_name = fakegen.company()
webpg = webpage.objects.get_or_create(topic=top, url=fake_ur, name=fake_name)[0]
acc_rec = AccessRecord.object.get_or_create(name=webpg,date=fake_date)[0]
if __name__ == ' __main__':
print("populate")
populate(20)
print("populating complete!")
please what do I do?
i ran the whole code in my terminal and it populated the database
Hi I'm trying to test mock django-filer save() that trigger post_save signal.
models.py
import filer.fields.file import FilerFileField
class DeliveryInvoice(TimeStampedModel):
invoice_excel = FilerFileField(null=True, blank=True)
tests.py
from filer.models.filemodels import File as FilerFile
from django.core.files import File
def test_if_delivery_invoice_number_updated_on_file_save_through_admin(self):
with patch("orders.utils.apply_invoice_number_to_orders") as signal_mock_handler:
post_save.connect(signal_mock_handler, sender=DeliveryInvoice)
filename = 'test_invoice_excel'
filepath = 'orders/fixtures/delivery_invoices.xlsx'
with open(filepath, 'rb') as f:
file_obj = File(f, name=filename)
error -> invoice_excel = FilerFile.objects.create(owner=self.user, file=file_obj, original_filename=filename)
instance = DeliveryInvoice(invoice_excel=invoice_excel)
instance.save()
self.assertTrue(signal_mock_handler.called)
Error Message
....
File "/Users/mhjeon/.pyenv/versions/3.6.0/envs/modernlab/lib/python3.6/site-packages/boto/auth.py", line 1070, in _wrapper
if test in self.host:
TypeError: argument of type 'NoneType' is not iterable
The code used to work a few days ago, but after some code refactoring which I believe is not related to the orders models, it suddenly fail to calle the django-filer's FilerModel.save() method.
What could be wrong?/
I want to get ATR of the smartcard. I am using HID omnikey 5321. I am following this link "http://pyscard.sourceforge.net/user-guide.html#requesting-any-card"
so far i have tried:
>>>from smartcard.CardType import AnyCardType
>>>from smartcard.CardRequest import CardRequest
>>>from smartcard.util import toHexString
>>>
>>> cardtype = AnyCardType()
>>> cardrequest = CardRequest( timeout=1, cardType=cardtype )
>>> cardservice = cardrequest.waitforcard()
>>>
>>>>>> cardservice.connection.connect()
i am getting error at the
cardservice.connection.connect()
error like:
raise CardConnectionException('Unable to connect with ptotocol[pcscprotocol] + . '+ScardGetErrorMessage(hresult)
CardConnectionException: Unable to conenct the card with T0 or T1 . Card is not responding to reset.
Because You dont specify the reader to connect:
r=readers()
#r[Number of reader list].
cardservice.connection = r[0].createConnection()
cardservice.connection.connect()
A simple Example:
from __future__ import print_function
from smartcard.Exceptions import NoCardException
from smartcard.System import readers
from smartcard.util import toHexString
for reader in readers():
try:
connection = reader.createConnection()
connection.connect()
print(reader, toHexString(connection.getATR()))
except NoCardException:
print(reader, 'no card inserted')
import sys
if 'win32' == sys.platform:
print('press Enter to continue')
sys.stdin.read(1)
-Another Selecting Reader:
from __future__ import print_function
from smartcard.Exceptions import NoCardException
from smartcard.System import readers
from smartcard.util import toHexString
from smartcard.CardType import AnyCardType
from smartcard.CardRequest import CardRequest
cardtype = AnyCardType()
r=readers()
cardrequest = CardRequest( timeout=10, cardType=cardtype )
cardservice = cardrequest.waitforcard()
print('Available Readers:')
for i in range(len(readers())):
print('[',i+1,']',r[i])
if(len(readers()) < 1):
print("\nNO AVAILABLE READERS!\n")
else:
print("Select you Reader: (Ctrl+C to Exit)")
my_input = input()
selectReader = clamp(int(my_input)-1,0,len(readers()))
print('Selected: ',r[selectReader])
cardservice.connection = r[selectReader].createConnection()
cardservice.connection.connect()
try:
print('Card ATR:',toHexString(cardservice.connection.getATR()),file=f)
except:
print("Cant not Get ATR")
.
Full Information:
https://pyscard.sourceforge.io/pyscard-framework.html#framework-samples
https://github.com/LudovicRousseau/pyscard
https://pyscard.sourceforge.io/user-guide.html
In python, you can use the pyscard library to interact with smart cards, there is an example that should help you display the ATR at http://pyscard.sourceforge.net/pyscard-framework.html#framework-samples
I have 2 simple models:
class UploadImage(models.Model):
Image = models.ImageField(upload_to="temp/")
class RealImage(models.Model):
Image = models.ImageField(upload_to="real/")
And one form
class RealImageForm(ModelForm):
class Meta:
model = RealImage
I need to save file from UploadImage into RealImage. How could i do this.
Below code doesn't work
realform.Image=UploadImage.objects.get(id=image_id).Image
realform.save()
Tnx for help.
Inspired by Gerard's solution I came up with the following code:
from django.core.files.base import ContentFile
#...
class Example(models.Model):
file = models.FileField()
def duplicate(self):
"""
Duplicating this object including copying the file
"""
new_example = Example()
new_file = ContentFile(self.file.read())
new_file.name = self.file.name
new_example.file = new_file
new_example.save()
This will actually go as far as renaming the file by adding a "_1" to the filename so that both the original file and this new copy of the file can exist on disk at the same time.
Although this is late, but I would tackle this problem thus,
class UploadImage(models.Model):
Image = models.ImageField(upload_to="temp/")
# i need to delete the temp uploaded file from the file system when i delete this model
# from the database
def delete(self, using=None):
name = self.Image.name
# i ensure that the database record is deleted first before deleting the uploaded
# file from the filesystem.
super(UploadImage, self).delete(using)
self.Image.storage.delete(name)
class RealImage(models.Model):
Image = models.ImageField(upload_to="real/")
# in my view or where ever I want to do the copying i'll do this
import os
from django.core.files import File
uploaded_image = UploadImage.objects.get(id=image_id).Image
real_image = RealImage()
real_image.Image = File(uploaded_image, uploaded_image.name)
real_image.save()
uploaded_image.close()
uploaded_image.delete()
If I were using a model form to handle the process, i'll just do
# django model forms provides a reference to the associated model via the instance property
form.instance.Image = File(uploaded_image, os.path.basename(uploaded_image.path))
form.save()
uploaded_image.close()
uploaded_image.delete()
note that I ensure the uploaded_image file is closed because calling real_image.save() will open the file and read its content. That is handled by what ever storage system is used by the ImageField instance
Try doing that without using a form. Without knowing the exact error that you are getting, I can only speculate that the form's clean() method is raising an error because of a mismatch in the upload_to parameter.
Which brings me to my next point, if you are trying to copy the image from 'temp/' to 'real/', you will have to do a some file handling to move the file yourself (easier if you have PIL):
import Image
from django.conf import settings
u = UploadImage.objects.get(id=image_id)
im = Image.open(settings.MEDIA_ROOT + str(u.Image))
newpath = 'real/' + str(u.Image).split('/', 1)[1]
im.save(settings.MEDIA_ROOT + newpath)
r = RealImage.objects.create(Image=newpath)
Hope that helped...
I had the same problem and solved it like this, hope it helps anybody:
# models.py
class A(models.Model):
# other fields...
attachment = FileField(upload_to='a')
class B(models.Model):
# other fields...
attachment = FileField(upload_to='b')
# views.py or any file you need the code in
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from django.core.files.base import ContentFile
from main.models import A, B
obj1 = A.objects.get(pk=1)
# You and either copy the file to an existent object
obj2 = B.objects.get(pk=2)
# or create a new instance
obj2 = B(**some_params)
tmp_file = StringIO(obj1.attachment.read())
tmp_file = ContentFile(tmp_file.getvalue())
url = obj1.attachment.url.split('.')
ext = url.pop(-1)
name = url.pop(-1).split('/')[-1] # I have my files in a remote Storage, you can omit the split if it doesn't help you
tmp_file.name = '.'.join([name, ext])
obj2.attachment = tmp_file
# Remember to save you instance
obj2.save()
Update Gerard's Solution to handle it in a generic way:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from django.core.files.base import ContentFile
init_str = "src_obj." + src_field_name + ".read()"
file_name_str = "src_obj." + src_field_name + ".name"
try:
tmp_file = StringIO(eval(str(init_str)))
tmp_file = ContentFile(tmp_file.getvalue())
tmp_file.name = os.path.basename(eval(file_name_str))
except AttributeError:
tmp_file = None
if tmp_file:
try:
dest_obj.__dict__[dest_field_name] = tmp_file
dest_obj.save()
except KeyError:
pass
Variable's Used:
src_obj = source attachment object.
src_field_name = source attachment object's FileField Name.
dest_obj = destination attachment object.
dest_field_name = destination attachment object's FileField Name.