2014-11-04 75 views
0

這是我的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的順序,但有不差

+0

你的'download_image'應該在調用它的函數之前。 def的順序應該是:第一個valid_img,第二個download_image,其餘的第三個......以及:圖像的所有者是誰?對文件夾/文件具有Apache/Nginx/Django權限? – AlvaroAV 2014-11-04 12:11:03

+0

請你可以修復模型中的縮進嗎?我不知道'download_image'是否在課堂內部。 – 2014-11-04 12:11:07

+0

和@Liarez:不,職能順序並不重要。 – 2014-11-04 12:11:27

回答

1

由於您的函數是Post的方法,因此您需要像這樣調用它們。方法總是通過實例引用,因此在這種情況下self.download_image(url),並且始終需要以self作爲第一個參數,因此def download_image(self, url)。這兩個也適用於valid_img

請注意,重寫save方法的簽名是一個非常糟糕的主意。 Django和第三方應用程序中的大量代碼都不會期待這個參數。相反,從kwargs得到它:

def save(self, *args, **kwargs): 
    url = kwargs.pop('url', '') 
+0

我不認爲kwargs的作品,給我一個空的網址。 – 2014-11-04 12:56:17

1

如果你想使一個對象的方法,第一個參數應該是自我,如果你可以調用通過self.download_image(...)方法

你也應該寫裏面的方法download_image保存方法,想要這樣使用。

def save(self, ...): 
    def download_image(): 
     ... 
    download_image() 
相關問題