Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unresolved reference to self for class function

Tags:

python

django

Why is my IDE telling me that there is an Unresolved reference to self in the line:

-->  photo = models.ImageField(upload_to=self.upload_path)

Code:

class Photo(models.Model):
    title = models.CharField(max_length=50, blank=True)
    album = models.ForeignKey(Album)
    photo = models.ImageField(upload_to=self.upload_path)
    upload = models.DateTimeField(auto_now_add=True)

    def upload_path(self, filename):
        title = self.album.title
        if " " in title:
            title.replace(" ", "_")
        return os.path.join(title, filename)

This error doesn't show up when I put the upload_path function outside the class. However, I want the function inside the class to try to keep things neat.

No IDE error but I am not sure why.

def upload_path(self, filename):
    title = self.album.title
    if " " in title:
        title.replace(" ", "_")
    return os.path.join(title, filename)


class Photo(models.Model):
    title = models.CharField(max_length=50, blank=True)
    album = models.ForeignKey(Album)
    photo = models.ImageField(upload_to=upload_path)
    upload = models.DateTimeField(auto_now_add=True)
like image 207
Liondancer Avatar asked May 23 '15 23:05

Liondancer


1 Answers

self can only be used inside class methods which define it as a parameter.

In this case, you need to treat the method as an unbound method (without giving the value for self), because Django itself will pass in the instance as the first parameter:

class Photo(models.Model):
    def upload_path(self, filename):
        ....

    photo = models.ImageField(upload_to=upload_path)

Note that because you are using upload_path inside the class definition itself, the usage must come after the definition of upload_path.

Edit:

According to this bug report, there is a limitation in Django's migration system on Python 2.x, which will cause it not to work with the above code, even though the code itself is correct. You will have to put the function outside the class in order to use migrations.

The documentation states:

If you are using Python 2, we recommend you move your methods for upload_to and similar arguments that accept callables (e.g. default) to live in the main module body, rather than the class body.

like image 162
interjay Avatar answered Sep 22 '22 02:09

interjay