Reputation: 43
I am developing an app, and one of its features is that it can recognize the device, but sometimes it doesn't get anything back. It maybe an error from the API that i'm using.
The model Device is the following:
class Device(models.Model):
"""
"""
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
deviceModel = models.CharField(max_length=128, verbose_name=_(u"Device Model"))
deviceId = models.CharField(max_length=128, verbose_name=_(u"Device ID"))
packageId = models.CharField(max_length=128, verbose_name=_(u"Package ID"))
tokenId = models.TextField(verbose_name=_(u"Token ID"))
platformId = models.CharField(max_length=10, verbose_name=_(u"Plataforma ID"))
created_at = models.DateTimeField(auto_now=True, verbose_name=_(u"Created"))
updated_at = models.DateTimeField(auto_now=True, verbose_name=_(u"Updated"))
def __str__(self):
return u'Device: {0}'.format(self.deviceId)
def __unicode__(self):
return self.__str__()
def send_logout(self):
"""
Send logout Notification Message
"""
active_session = ActiveSession.objects.filter(
device=self
).first()
if active_session:
push_service = FCMNotification(api_key=settings.FCM_API_KEY)
data_message = {
"action": "Logout",
"token_id": active_session.token_jwt
}
push_service.single_device_data_message(
registration_id=self.tokenId,
data_message=data_message,
content_available=True
)
And the serializer is:
class DeviceSerializer(ModelSerializer):
def create(self, validated_data):
# Check if exist
device = Device.objects.filter(user=validated_data["user"], deviceId=validated_data['deviceId']).first()
today = timezone.now()
# If exist, update
if device:
device.tokenId = validated_data['tokenId']
device.updated_at = today
device.save()
logger.info("[Device] Updated deviceID {} with token {} for user {}".format(
validated_data['deviceId'],
validated_data['tokenId'],
validated_data["user"].username
))
else:
device = Device(**validated_data)
device.save()
logger.info("[Device] Created deviceID {} with token {} for user {}".format(
validated_data['deviceId'],
validated_data['tokenId'],
validated_data["user"].username
))
# Associate Device to ActiveSession
active_session = ActiveSession.get_active_session(self.context.get('request'))
active_session.device = device
active_session.save()
return device
class Meta:
model = Device
fields = ("id", "deviceModel", "deviceId", "packageId", "tokenId", "platformId")
The error that i get comes from this line active_session.device = device
I want to face this error by creating an exception for this AttributeError
. But my mind is open for ideas.
The full traceback is this:
[ERROR] 15:12 Internal Server Error: /api/device/
Traceback (most recent call last):
File "/home/user/.local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/home/user/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/user/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/user/.local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/user/.local/lib/python2.7/site-packages/rest_framework/viewsets.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
File "/home/user/.local/lib/python2.7/site-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/home/user/.local/lib/python2.7/site-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/user/.local/lib/python2.7/site-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/home/user/Downloads/ID/id/modules/api/views.py", line 69, in create
self.perform_create(serializer)
File "/home/user/Downloads/ID/id/modules/api/views.py", line 78, in perform_create
serializer.save(user=self.request.user)
File "/home/user/.local/lib/python2.7/site-packages/rest_framework/serializers.py", line 214, in save
self.instance = self.create(validated_data)
File "/home/user/Downloads/ID/id/modules/api/serializers.py", line 65, in create
active_session.device_test = device
AttributeError: 'NoneType' object has no attribute 'device_test'
Upvotes: 0
Views: 72
Reputation: 127
A AttributeError can happens in many cases, but is frequently happen when is try doing a wrong association with a related model. In this case, if your ActionveSessionModel has a different related_name to 'device', the 'device' does not be found.
https://github.com/django/django/blob/master/django/db/models/fields/related_descriptors.py#L98
Upvotes: 1