2

I've seen other questions about this error but none of them were able to help so I figured I make on myself. As per the title, I keep getting this type error and I have run out of ideas as to why it is occurring.

I am making an app that involves a Gallery object that adds Photo objects. What I have been specifically working on recently was a zip_upload function in order to add photos from a .zip file. I have tried Photologue but I am deciding to handle everything myself for multiple reasons. Actually, I referred to Photologue a lot when writing it so there any many similarities. Here is my code(left out unimportant details) and traceback:

Models:

from django.utils.timezone import now

class ImageModel(models.Model):
  image = models.ImageField('image',max_length=100,upload_to='photos')
  class Meta:
      abstract = True

class Photo(ImageModel):
  title = models.CharField('title',max_length=250,unique=True)
  date_added = models.DateTimeField('date added',default=now)
  objects = PhotoQuerySet.as_manager()

class Gallery(models.Model):
  title = models.CharField('title',max_length=250,unique=True)
  photos = models.ManyToManyField(Photo,
             related_name='gallery',verbose_name='photos', blank=True)
  objects = GalleryQuerySet.as_manager()

Admin page:

class GalleryAdmin(admin.ModelAdmin):

    def get_urls(self):
        urls = super(GalleryAdmin, self).get_urls()
        add_urls = [
            url(r'^upload_zip/$',
                self.admin_site.admin_view(self.upload_zip),
                name='upload_zip')
        ]
        return add_urls + urls

    def upload_zip(self,request):
        context = {
            'app_label': self.model._meta.app_label,
            'opts': self.model._meta,
        }

        # Handle form request
        if request.method == 'POST':
            form = UploadZipForm(request.POST, request.FILES)
            if form.is_valid():
                form.save(request=request)
                return HttpResponseRedirect('..')
        else:
            form = UploadZipForm()
        context['form'] = form
        context['adminform'] = helpers.AdminForm(form,
                         list([(None{'fields':form.base_fields})]),{})
        return render(
            request,'admin/inv_app/gallery/upload_zip.html',context)

Form:

class UploadZipForm(forms.Form):
  zip_file = forms.FileField()
  title = forms.CharField(label='Title',required=False)
  gallery = forms.ModelChoiceField(Gallery.objects.all(),
        label='Gallery',required=False,)

  # left out methods that check if zip_file is valid and titles have 
  # not been used by other Gallery objects

  def save(self, request=None, zip_file=None):
    if not zip_file:
        zip_file = self.cleaned_data['zip_file']
      zip = zipfile.ZipFile(zip_file,'r')
      count = 1
      if self.cleaned_data['gallery']:
          logger.debug('Using pre-existing gallery.')
          gallery = self.cleaned_data['gallery']
      else:
          logger.debug(
            force_text('Creating new gallery "{0}".')
                 .format(self.cleaned_data['title']))
          gallery = Gallery.objects.create(
            title=self.cleaned_data['title'],
            slug=slugify(self.cleaned_data['title']),)
      found_image = False
    for filename in sorted(zip.namelist()):
        _, file_extension = os.path.splitext(filename)
        file_extension = file_extension.lower()
        if not file_extension or file_extension != '.jpg':
            continue
        # check file is not subfolder

        data = zip.read(filename)

        # check file is not empty, assign title to photo

        contentfile = ContentFile(data)
        photo.image.save(filename, contentfile)
        # I believe the error is produced here ^
        photo.save()
        gallery.photos.add(photo)
    zip.close()

Traceback:

File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  response = self.process_exception_by_middleware(e, request)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response 
  response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
  response = view_func(request, *args, **kwargs)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  response = view_func(request, *args, **kwargs)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/contrib/admin/sites.py" in inner
  return view(request, *args, **kwargs)
File "/Users/Lucas/Documents/inventory-master/inv_app/admin.py" in upload_zip
  form.save(request=request)
File "/Users/Lucas/Documents/inventory-master/inv_app/forms.py" in save
  photo.image.save(filename, contentfile)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/fields/files.py" in save
  self.instance.save()
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/base.py" in save
  force_update=force_update, update_fields=update_fields)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/base.py" in save_base
  updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/base.py" in _save_table
  result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/base.py" in _do_insert
  using=using, raw=raw)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method
  return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/query.py" in _insert
  return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in execute_sql
  for sql, params in self.as_sql():
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in as_sql
  for obj in self.query.objs
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in <listcomp>
  for obj in self.query.objs
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in <listcomp>
  [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in prepare_value
  value = field.get_db_prep_save(value, connection=self.connection)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save
  prepared=False)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value
  value = self.get_prep_value(value)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in get_prep_value
  value = super(DateTimeField, self).get_prep_value(value)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in get_prep_value
  return self.to_python(value)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in to_python
  parsed = parse_datetime(value)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/utils/dateparse.py" in parse_datetime
  match = datetime_re.match(value)

Exception Type: TypeError at /admin/inv_app/gallery/upload_zip/
Exception Value: expected string or bytes-like object

I am relatively new to web dev so I'm sure I'm missing something minuscule or obvious. Please help!

2
  • In the error page, Django will also show you the values of all variables in the stack. What are the values of filename and contentfile in the execution of inv_app.forms.save? Commented Sep 12, 2016 at 7:12
  • @skoll filename: 'rings/ring2.jpg' and contentfile: <ContentFile: Raw content> ring2 is the first image in the zip file I am testing Commented Sep 12, 2016 at 14:35

1 Answer 1

1

Well I was able to solve it on my own!

My problem was the way I was overriding the Photo model's save method:

def save(self, *args, **kwargs):
    if self.slug is None:
        self.slug = slugify(self.title)
    super(Photo, self).save(*args, **kwargs)

For some reason it was not saving properly so removing it fixed the bug and it works the way it should now. I figured I did not really need to override it so I did not need to replace it! I am realizing I did not post this portion of the model in my original question so that is my mistake for not trying to completely understand the error before posting.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.