我是编程和 Django 的初学者,所以我很感激初学者可以帮助他!
我正在按照教程展示如何使用 Boto 库将图像上传到 Amazon S3 帐户,但我认为它适用于较旧版本的 Django(我使用的是 1.1.2 和 Python 2.65),并且发生了一些变化。我收到一个错误:异常类型:TypeError 异常值:'InMemoryUploadedFile' 对象不可订阅
我的代码是:
模型.py:
from django.db import models
from django.contrib.auth.models import User
from django import forms
from datetime import datetime
class PhotoUrl(models.Model):
url = models.CharField(max_length=128)
uploaded = models.DateTimeField()
def save(self):
self.uploaded = datetime.now()
models.Model.save(self)
视图.py:
import mimetypes
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from django import forms
from django.conf import settings
from boto.s3.connection import S3Connection
from boto.s3.key import Key
def awsdemo(request):
def store_in_s3(filename, content):
conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
b = conn.create_bucket('almacmillan-hark')
mime = mimetypes.guess_type(filename)[0]
k = Key(b)
k.key = filename
k.set_metadata("Content-Type", mime)
k.set_contents_from_strong(content)
k.set_acl("public-read")
photos = PhotoUrl.objects.all().order_by("-uploaded")
if not request.method == "POST":
f = UploadForm()
return render_to_response('awsdemo.html', {'form':f, 'photos':photos})
f = UploadForm(request.POST, request.FILES)
if not f.is_valid():
return render_to_response('awsdemo.html', {'form':f, 'photos':photos})
file = request.FILES['file']
filename = file.name
content = file['content']
store_in_s3(filename, content)
p = PhotoUrl(url="http://almacmillan-hark.s3.amazonaws.com/" + filename)
p.save()
photos = PhotoUrl.objects.all().order_by("-uploaded")
return render_to_response('awsdemo.html', {'form':f, 'photos':photos})
网址.py:
(r'^awsdemo/$', 'harkproject.s3app.views.awsdemo'),
awsdemo.html:
<div class="form">
<strong>{{form.file.label}}</strong>
<form method="POST" action ="." enctype="multipart/form-data">
{{form.file}}<br/>
<input type="submit" value="Upload">
</form>
</div>
我真的很感激帮助。我希望我已经提供了足够的代码。
亲切的问候 AL