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:
我正在开发一个应用程序,其中包含一个添加照片对象的Gallery对象。我最近特别开发的是zip_upload函数,用于从.zip文件中添加照片。我已经试过了,但是我决定自己处理所有事情的原因有很多。实际上,我在写这篇文章的时候经常提到Photologue,所以有很多相似之处。这是我的代码(漏掉了不重要的细节)和回溯:
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!
我对web开发比较陌生,所以我肯定我漏掉了一些微不足道或显而易见的东西。请帮助!
1 个解决方案
#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.
由于某些原因,它没有正确地保存,所以删除它修复了bug,并且按照现在应该的方式工作。我想我真的不需要重写它,所以我不需要替换它!我意识到我没有在我的原始问题中发布这部分模型,所以这是我的错误,因为我没有试图在发布之前完全理解错误。
#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.
由于某些原因,它没有正确地保存,所以删除它修复了bug,并且按照现在应该的方式工作。我想我真的不需要重写它,所以我不需要替换它!我意识到我没有在我的原始问题中发布这部分模型,所以这是我的错误,因为我没有试图在发布之前完全理解错误。