Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 名称错误:名称';下载图片';没有定义_Python_Django_Nameerror - Fatal编程技术网

Python 名称错误:名称';下载图片';没有定义

Python 名称错误:名称';下载图片';没有定义,python,django,nameerror,Python,Django,Nameerror,这是我的models.py文件 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=Tru

这是我的models.py文件

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
我确实尝试过更改def的顺序,但没有区别

如果您想创建对象方法,第一个参数应该是self,您可以通过self调用方法。下载图片(…)

如果您想这样使用,还应该在save方法中编写download_image方法

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

因为函数是Post方法,所以需要这样调用它们。方法总是通过实例引用,因此在本例中
self.download\u image(url)
,并且总是需要将
self
作为第一个参数,因此
def download\u image(self,url)
。这两项也适用于
有效的\u img

还要注意,重写save方法的签名是一个非常糟糕的主意。Django和第三方应用程序中的许多代码都不需要该参数。相反,请从kwargs获得:

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

您的
下载\u图像
应该在调用它的函数之前。def的顺序应该是:第一个有效图片,第二个下载图片,第三个剩余。。。还有:谁是这些图像的所有者?对文件夹/文件拥有Apache/Nginx/Django权限?请修复模型中的缩进?我不知道下载图片是否在类中。而且@Liarez:不,函数的顺序不重要。@DanielRoseman我相信你,因为你有更多的经验,但我记得我在一些项目中遇到过一些问题,如果函数在调用它的函数之前没有定义,那么使用函数1)您需要在每行前面加上4个空格才能正确显示它。2) 似乎可以假定
download\u image
Post
模型的一种方法,因为在文件的底部有一种
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。3) 在这种情况下,您必须调用
self.download\u image
(这是一个实例方法),这个问题应该得到解决。