Как исправить «TypeError: ожидаемую строку или байтовоподобный объект» при использовании Amazon S3 с Pillow на Django - PullRequest
1 голос
/ 17 октября 2019

Я пытаюсь загрузить изображение, отредактированное через подушку, в Amazon S3 - я прошел через все настройки, но, похоже, он не работает.

Это моя модель:

import uuid
import qrcode
from PIL import Image
from io import BytesIO
from django.core.files import File


BOOL_CHOICES = ((True, 'Attended'), (False, 'Absent'))

class Person(models.Model):
    userid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True)
    first_Name = models.CharField(default=" ", max_length=50)
    last_Name = models.CharField(default=" ", max_length=50)
    email = models.EmailField()
    number_of_Guests = models.PositiveIntegerField(default=0)
    url_link = models.CharField(default=' ', max_length=200)
    qr_image = models.ImageField(upload_to='qrcodes', default='default.jpg')
    attended = models.BooleanField(default = False, choices=BOOL_CHOICES)

    def __str__(self):
        return (self.first_Name + " " + self.last_Name + " " + str(self.userid))

    def save(self, *args, **kwargs):
        self.url_link = "mywebsite.com/" + str(self.userid)
        img = qrcode.make(self.url_link)
        canvas = Image.new('RGB', (500, 500), 'white')
        canvas.paste(img)
        blob = BytesIO()
        canvas.save(blob, 'JPEG')

        self.qr_image.save('qr-' + str(self.userid) + '.jpg', File(blob))
        super().save(*args, **kwargs)

Traceback:



Request Method: POST
Request URL: http://127.0.0.1:8000/tickets/

Django Version: 2.2.6
Python Version: 3.6.5
Installed Applications:
['event.apps.EventConfig',
 'tickets.apps.TicketsConfig',
 'crispy_forms',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'paypal.standard.ipn',
 'storages']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')



Traceback:

File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/koheisanno/galanighttassel/tickets/views.py" in buy
  74.             form.save()

File "/anaconda3/lib/python3.6/site-packages/django/forms/models.py" in save
  458.             self.instance.save()

File "/Users/koheisanno/galanighttassel/event/models.py" in save
  39.         self.qr_image.save('qr-' + str(self.userid) + '.jpg', File(blob))

File "/anaconda3/lib/python3.6/site-packages/django/db/models/fields/files.py" in save
  87.         self.name = self.storage.save(name, content, max_length=self.field.max_length)

File "/anaconda3/lib/python3.6/site-packages/django/core/files/storage.py" in save
  51.         name = self.get_available_name(name, max_length=max_length)

File "/anaconda3/lib/python3.6/site-packages/storages/backends/s3boto3.py" in get_available_name
  620.         return super(S3Boto3Storage, self).get_available_name(name, max_length)

File "/anaconda3/lib/python3.6/site-packages/django/core/files/storage.py" in get_available_name
  75.         while self.exists(name) or (max_length and len(name) > max_length):

File "/anaconda3/lib/python3.6/site-packages/storages/backends/s3boto3.py" in exists
  520.             self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name)

File "/anaconda3/lib/python3.6/site-packages/botocore/client.py" in _api_call
  357.             return self._make_api_call(operation_name, kwargs)

File "/anaconda3/lib/python3.6/site-packages/botocore/client.py" in _make_api_call
  634.             api_params, operation_model, context=request_context)

File "/anaconda3/lib/python3.6/site-packages/botocore/client.py" in _convert_to_request_dict
  680.             api_params, operation_model, context)

File "/anaconda3/lib/python3.6/site-packages/botocore/client.py" in _emit_api_params
  712.             params=api_params, model=operation_model, context=context)

File "/anaconda3/lib/python3.6/site-packages/botocore/hooks.py" in emit
  356.         return self._emitter.emit(aliased_event_name, **kwargs)

File "/anaconda3/lib/python3.6/site-packages/botocore/hooks.py" in emit
  228.         return self._emit(event_name, kwargs)

File "/anaconda3/lib/python3.6/site-packages/botocore/hooks.py" in _emit
  211.             response = handler(**kwargs)

File "/anaconda3/lib/python3.6/site-packages/botocore/handlers.py" in validate_bucket_name
  219.     if VALID_BUCKET.search(bucket) is None:

Exception Type: TypeError at /tickets/
Exception Value: expected string or bytes-like object

Возможно, это не проблема с подушкой, потому что она говорит, что не может найти правильное ведро? Я несколько раз проверял, правильно ли набираются названия моих корзин.

Спасибо!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...