2014-11-04 5 views
0

를 정의되지 않은 이름 'download_image은'이건 내 models.py 파일나가서 설명하자면 NameError :

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(){} 
     }); 
63,210

브라우저 콘솔에서 나는군요이

POST http://localhost:8000/create/ 500 (INTERNAL SERVER ERROR) 

기원 또는이 문제가 될 수있다 누군가가 이해할 수 있다면 도와주세요 : D 나는 인증 된 정의의 순서를 변경하려고했지만이 있었다 하지 차이

+0

'download_image'는 그것을 호출하는 함수보다 먼저 있어야합니다. def의 순서는 다음과 같아야합니다. 첫 번째 valid_img, 두 번째 download_image, 나머지 세 번째 ... 그리고 : 이미지의 소유자는 누구입니까? 폴더/파일에 대한 Apache/Nginx/Django 권한이 있습니까? – AlvaroAV

+0

들여 쓰기를 모델에서 수정할 수 있습니까? 'download_image'가 클래스 안에 있는지 아닌지 알 수 없습니다. –

+0

그리고 @Liarez : 아니요, 함수의 순서는 중요하지 않습니다. –

답변

1

함수는 게시물의 메소드이므로 해당 함수를 호출해야합니다. 메서드는 항상 인스턴스를 통해 참조되므로이 경우 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 부분이 작동하지 않는다고 생각합니다. 빈 URL을 제공합니다. –

1

하면 객체 방법을 확인하려면 첫 번째 매개 변수는 스스로해야하고이 경우, 당신은 방법 저장 내부 download_image 방법을 작성해야

또한

self.download_image (...)를 통해 메소드를 호출 할 수 이런 식으로 사용하고 싶습니다.

def save(self, ...): 
    def download_image(): 
     ... 
    download_image()