Although I have read many similar articles about PointField
and 'NoneType' object error
, I can't figure out how this field should be automatically save according to the latitude and longitude variables I received from the user.
Here is my model:
from django.db import models
from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
class Firm(models.Model):
FirmName = models.CharField(max_length=50)
address = models.CharField(max_length=1000, null=True, blank=True)
FirmAddress = models.PointField(null=True, blank = True, geography=True, default=Point(0.0, 0.0))
lat = models.FloatField(null=True, blank=True)
lng = models.FloatField(null=True, blank=True)
Logo = models.ImageField(null=True, blank=True)
@property
def save(self, *args, **kwargs):
self.FirmAddress = Point(self.lng, self.lat)
super(Firm, self).save(*args, **kwargs)
On the Django shell, I type
from firm.models import Firm
command first and then
Firm.objects.create(FirmName="QWERTY", address="temp", lat=24, lng=54, Logo='logo.jpg')
command.
Here is the error I got at the end:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\Deniz\Desktop\PROJECT\fenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Deniz\Desktop\PROJECT\fenv\lib\site-packages\django\db\models\query.py", line 453, in create
obj.save(force_insert=True, using=self.db)
TypeError: 'NoneType' object is not callable
But when I look at my database, I see that a value of type geography-point has been added to the FirmAddress
column. When I remove the FirmAddress feature and update the model, I don't get any errors and everything works fine.
The part I'm having trouble understanding is, if FirmAddress data can be added to the database correctly, why am I getting the 'NoneType' object
error? How can I fix this situation? Many thanks.
Why am I getting the 'NoneType' object error?
Because you defined save
as a @property
. As a result if you use self.save
, it will call the save method, and self.save
will take as value what the object returned, but that is None
, hence the error.
You thus should remove the @property
decorator:
class Firm(models.Model):
# …
# no property
def save(self, *args, **kwargs):
self.FirmAddress = Point(self.lng, self.lat)
return super().save(*args, **kwargs)