title: NameError: name 'download_image' is not defined
body: <p>this is my models.py file</p>
  
  <pre><code>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
  </code></pre>
  
  <p>and my view.py is</p>
  
  <pre><code>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))
  </code></pre>
  
  <p>and this is where the url gets called </p>
  
  <pre><code>$.ajax({
        type: "POST",
        url: "/create/",
        data: {'url': newURL, 'csrfmiddlewaretoken': csrftoken},
        success: function(){}
        });
  </code></pre>
  
  <p>in the console I am getting this </p>
  
  <pre><code>in save
  NameError: name 'download_image' is not defined
  </code></pre>
  
  <p>and in the browser console I'm getting this</p>
  
  <pre><code>POST http://localhost:8000/create/ 500 (INTERNAL SERVER ERROR) 
  </code></pre>
  
  <p>If anyone can understand where the origin or this problem may be please help :D
  I did try changing the order of the defs but there was not difference</p>