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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With