這是我的models.py文件NameError:名字 'download_image' 沒有定義
class Post(models.Model):
"""docstring for Post"""
poster = models.ForeignKey(User, null= False,blank=True, default=User.objects.get(username="admin"))
post_image = models.ImageField(upload_to='posts', null=True, blank=True)
def save(self, url='', *args, **kwargs):
if self.post_image != '' and url != '': # Don't do anything if we don't get passed anything!
image = download_image(url) # See function definition below
try:
filename = urlparse.urlparse(url).path.split('/')[-1]
self.post_image = filename
tempfile = image
tempfile_io = io.StringIO() # Will make a file-like object in memory that you can then save
tempfile.save(tempfile_io, format=image.format)
self.post_image.save(filename, ContentFile(tempfile_io.getvalue()), save=False) # Set save=False otherwise you will have a looping save method
except Exception as e:
print ("Error trying to save model: saving image failed: " + str(e))
pass
super(Post, self).save(*args, **kwargs)
def download_image(url):
"""Downloads an image and makes sure it's verified.
Returns a PIL Image if the image is valid, otherwise raises an exception.
"""
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0'} # More likely to get a response if server thinks you're a browser
r = urllib.Request(url, headers=headers)
request = urllib.urlopen(r, timeout=10)
image_data = io.StringIO(request.read()) # StringIO imitates a file, needed for verification step
img = Image.open(image_data) # Creates an instance of PIL Image class - PIL does the verification of file
img_copy = copy.copy(img) # Verify the copied image, not original - verification requires you to open the image again after verification, but since we don't have the file saved yet we won't be able to. This is because once we read() urllib2.urlopen we can't access the response again without remaking the request (i.e. downloading the image again). Rather than do that, we duplicate the PIL Image in memory.
if valid_img(img_copy):
return img
else:
# Maybe this is not the best error handling...you might want to just provide a path to a generic image instead
raise Exception('An invalid image was detected when attempting to save a Product!')
def valid_img(img):
"""Verifies that an instance of a PIL Image Class is actually an image and returns either True or False."""
type = img.format
if type in ('GIF', 'JPEG', 'JPG', 'PNG'):
try:
img.verify()
return True
except:
return False
else: return False
def __unicode__(self):
return self.post_image.url
和我view.py是
def createpost(request):
# Handle file upload
new_img_id = 0
if request.method == 'POST':
external_url = request.POST['url']
p = Post(poster=request.user)
p.save(external_url)
new_img_id=p.id
post = Post.objects.filter(id=new_img_id)
return render_to_response('create.html',{'post': post},context_instance=RequestContext(request))
,這是其中的URL被調用
$.ajax({
type: "POST",
url: "/create/",
data: {'url': newURL, 'csrfmiddlewaretoken': csrftoken},
success: function(){}
});
在控制檯我得到這個
in save
NameError: name 'download_image' is not defined
,並在瀏覽器控制檯我得到這個
POST http://localhost:8000/create/ 500 (INTERNAL SERVER ERROR)
如果任何人都可以明白的地方來源或此問題可能是請幫助:d 我也嘗試改變DEFS的順序,但有不差
你的'download_image'應該在調用它的函數之前。 def的順序應該是:第一個valid_img,第二個download_image,其餘的第三個......以及:圖像的所有者是誰?對文件夾/文件具有Apache/Nginx/Django權限? – AlvaroAV 2014-11-04 12:11:03
請你可以修復模型中的縮進嗎?我不知道'download_image'是否在課堂內部。 – 2014-11-04 12:11:07
和@Liarez:不,職能順序並不重要。 – 2014-11-04 12:11:27