我已经看到有关此错误的其他问题,但他们都没有能够提供帮助,所以我想我自己做了。根据标题,我不断收到这种类型错误,并且我已经没有关于它为什么会发生的想法。
我正在制作一个涉及添加Photo对象的Gallery对象的应用。我最近专门研究的是一个zip_upload函数,用于添加.zip文件中的照片。我曾尝试过Photologue,但由于种种原因,我决定自己处理所有事情。实际上,我在编写时很多时都提到了Photologue,所以有很多相似之处。这是我的代码(遗漏了不重要的细节)和追溯:
型号:
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()
管理员页面:
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)
形式:
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()
回溯:
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
我对网络开发相对较新,所以我确定我错过了一些微不足道或明显的东西。请帮忙!
答案 0 :(得分:1)
我能够自己解决它!
我的问题是我重写Photo模型的保存方法:
def save(self, *args, **kwargs):
if self.slug is None:
self.slug = slugify(self.title)
super(Photo, self).save(*args, **kwargs)
由于某种原因,它没有正确保存,所以删除它修复了错误,它的工作方式应该是现在的。我想我真的不需要覆盖它所以我不需要更换它!我意识到我没有在我的原始问题中发布这部分模型,因此我错误地认为在发布之前没有完全理解错误。