目前,我正在尝试让我的管理界面多上传工作。我正在使用他的博客中提供的代码Luril Garmash:http://garmoncheg.blogspot.de/2011/07/django-creating-multi-upload-form.html他正在使用非常好的jQuery插件来实现来自Sebastian Tschan的多重上传文件:http://blueimp.github.com/jQuery-File-Upload/,我也是。
好的,这是我的结构:
models.py:
class Photoalbum(models.Model):
event = models.OneToOneField(Event, help_text="Liste der Events ohne Fotoalbum")
date = models.DateField(auto_now=True)
facebook = models.BooleanField()
class PhotoalbumImage(models.Model):
album = models.ForeignKey(Photoalbum, related_name='images', null=True)
filename = models.CharField(max_length=60, blank=True, null=True, editable=False)
image = models.FileField(upload_to=storage, editable=False)
key_data = models.CharField(max_length=90, unique=True, blank=True, null=True, editable=False)
upload_date = models.DateTimeField(auto_now=True)我对change_form.html模板进行了扩展,以便在相册模型的添加/更改站点上显示jQuery多上传表单。
以下是视图逻辑:
views.py:
def multiuploader(request):
#getting file data for farther manipulations
file = request.FILES[u'files[]']
wrapped_file = UploadedFile(file)
filename = wrapped_file.name
file_size = wrapped_file.file.size
log.info ('Got file: "%s"' % str(filename))
#writing file manually into model
#because we don't need form of any type.
image = PhotoalbumImage()
image.filename=str(filename)
image.image=file
image.key_data = image.key_generate
image.save()
log.info('File saving done')
#getting thumbnail url using sorl-thumbnail
im = get_thumbnail(image, "80x80", quality=50)
thumb_url = im.url
#settings imports
try:
file_delete_url = settings.MULTI_FILE_DELETE_URL+'/'
file_url = settings.MULTI_IMAGE_URL+'/'+image.key_data+'/'
except AttributeError:
file_delete_url = 'multi_delete/'
file_url = 'multi_image/'+image.key_data+'/'
#generating json response array
result = []
result.append({"id":image.id,
"name":filename,
"size":file_size,
"url":file_url,
"thumbnail_url":thumb_url,
"delete_url":file_delete_url+str(image.pk)+'/',
"delete_type":"POST",})
response_data = json.dumps(result)
#checking for json data type
#big thanks to Guy Shapiro
if "application/json" in request.META['HTTP_ACCEPT_ENCODING']:
mimetype = 'application/json'
else:
mimetype = 'text/plain'
return HttpResponse(response_data, mimetype=mimetype)
else: #GET
return HttpResponse('Only POST accepted')对于插件上传的每个文件都会调用此方法。注意:文件上传会通过单击“开始上传”将文件从相册分别保存到文件系统和数据库中。
注意:我的相册添加/更改模板显示我的相册的多重上传程序,在顶部有“添加文件”和“开始上传”的图像,在底部有相册的表单字段和标准的django管理保存按钮。sry我不能提供图片,因为在我现在所在的地方,我的连接非常,非常慢(太慢)。
这就是我的问题开始的地方:文件被保存了,但相册没有。我需要一种保存方法来将相册的正确主键作为外键保存到每个保存的文件中。我的第一个想法是在session中处理这个问题,将所有保存的文件id保存到一个列表中,并在相册的post_save信号中,获取这些id并将正确的相册id保存到这些文件中。但我认为不应该在模型中访问会话。我的第二个想法是创建一个临时模型,例如UploadedPhotos,我在其中存储所有的文件id,并在post_save信号上为相册获取这些id。
感觉就是不对劲。我认为满足我的需求的最安全的方法是在创建完相册之后上传文件(在相册模型中点击保存之后)。然后,相册的主键将存在,我可以将其保存到每个文件中。但我不知道怎么让它工作。
非常感谢您提前给予的帮助。问候
发布于 2012-08-18 07:35:32
好了,我达到了我的要求,通过填充一个隐藏的表单字段与上传和保存的相册模型中的照片的id。这个字段是一个charfield,我把所有的id都放在里面,用"//“将它们分开,然后在相册的post_save信号上解析它。
https://stackoverflow.com/questions/12005195
复制相似问题