Update profile on login

70 views
Skip to first unread message

pastrufazio

unread,
Nov 8, 2018, 12:20:56 PM11/8/18
to Django users

Hi all,

I'm trying to update the field "date_activation" the first time a user log in.

This is the error I get when i try to run the code below

TypeError at /admin/login/ int() argument must be a string, a bytes-like object or a number, not 'ModelBase'

Any help would be really appreciated!





class Profile(models.Model):
    user
= models.OneToOneField(User, on_delete=models.CASCADE)
    location
= models.CharField(max_length=30, blank=True)
    birth_date
= models.DateTimeField(null=True, blank=True)
    date_activation
= models.DateTimeField(null=True, blank=True)


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
   
if created:
       
Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance
.profile.save()

@receiver(user_logged_in, sender=User)
def user_logged_in_callback(sender, user, request, **kwargs):
   
Profile.objects.filter(user=User).update(date_activation=datetime.now)



Michal Petrucha

unread,
Nov 9, 2018, 4:29:06 AM11/9/18
to Django users
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512

On Thu, Nov 08, 2018 at 09:17:30AM -0800, pastrufazio wrote:
>
> Hi all,
>
> I'm trying to update the field "date_activation" the first time a user log
> in.
>
> This is the error I get when i try to run the code below
>
> *TypeError at /admin/login/ int() argument must be a string, a bytes-like
> object or a number, not 'ModelBase'*
>
> Any help would be really appreciated!

Hi,

Could you please post the full stack trace rather than just the final
error message? That would make it easier to help you.

Cheers,
Michal

> class Profile(models.Model):
> user = models.OneToOneField(User, on_delete=models.CASCADE)
> location = models.CharField(max_length=30, blank=True)
> birth_date = models.DateTimeField(null=True, blank=True)
> date_activation = models.DateTimeField(null=True, blank=True)
>
>
> @receiver(post_save, sender=User)
> def create_user_profile(sender, instance, created, **kwargs):
> if created:
> Profile.objects.create(user=instance)
>
> @receiver(post_save, sender=User)
> def save_user_profile(sender, instance, **kwargs):
> instance.profile.save()
>
> @receiver(user_logged_in, sender=User)
> def user_logged_in_callback(sender, user, request, **kwargs):
> Profile.objects.filter(user=User).update(date_activation=datetime.now)
>
>
>
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/237c6adf-1d2c-4ce7-b8d6-60a7d827833a%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1

iQIcBAEBCgAGBQJb5VMbAAoJEHA7T/IPM/kl5AcP/jhCQmT9cJrOFyb36ABIz/+0
/7rcsAq5NCyUAi6g/R4tchDI5K0Yw7uW5LSHl9eDeph1EhCeg/7ZXj8l7z45s5bG
NxR8usfqic/N8gZHPpHDYjnMG/ZjimuiGVQLq8hBA4lRrhvtHv8/VchLuI8U8h23
vez5lu3D8tGDYhBVcMgagji+8to3QmAfc2XYcJVwjgzF/lVyFAxfEzEurVuOshec
GjYYzd/nd8ZNFcZKSNNlh/P7OIW4tmZQ9dheRUV05a9zoG1ETTMEoTk2wy9wawzb
WcvG21Vz2CynnJcooWcJqHDV0bG6CPJgeJqefvZZI+8Fuok2ZgND3JlhsrH89f/R
+MthbLc49DgY1wAOZqMTk31v8I6/+3HV+X69Xu5dnyLwBkT9yY9pdKGmeNyWkatc
xHsnvyHdQi/EBLNTWlyfqv4EPuLoYpYgZJloecrtVhNFxFj+p9IFChwplNHHD566
b7iAlZnhnkhFIfk4oAN7wBGtTqA7rlaVaMWzOPgRIcXj9HYW4k62eOIANjDBER5n
HTdaE63MmPnF/hO6Gl0P45fG+FjMiSwy5erXViyIUjv9j70YQ28IwdRBJCkMaKjZ
SJk+MtxFXnWMdK5CGqDpXjhlriUMMAm+TUL3Iz1mkM3JmXM59l95Njy0mw5jjz6l
xjHIhdIztIG/8kKN567n
=i1zJ
-----END PGP SIGNATURE-----

pastrufazio

unread,
Nov 9, 2018, 4:42:56 AM11/9/18
to Django users
Il giorno venerdì 9 novembre 2018 10:29:06 UTC+1, Michal Petrucha ha scritto:

Hi,

Could you please post the full stack trace rather than just the final
error message? That would make it easier to help you.

Cheers,
Michal


Sure, thanks!



Environment:


Request Method: POST
Request URL: http://localhost:4000/admin/login/?next=/admin/

Django Version: 1.11.16
Python Version: 3.6.5
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'card',
 'corsheaders',
 'allauth.socialaccount',
 'rest_auth',
 'rest_framework.authtoken',
 'django.contrib.sites',
 'allauth',
 'allauth.account',
 'rest_auth.registration']
Installed Middleware:
['corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/contrib/admin/sites.py" in login
  393.         return LoginView.as_view(**defaults)(request)

File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
  67.             return bound_func(*args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
  76.             return view(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
  63.                 return func.__get__(self, type(self))(*args2, **kwargs2)

File "/usr/local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
  67.             return bound_func(*args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
  63.                 return func.__get__(self, type(self))(*args2, **kwargs2)

File "/usr/local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
  67.             return bound_func(*args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
  63.                 return func.__get__(self, type(self))(*args2, **kwargs2)

File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/views.py" in dispatch
  90.         return super(LoginView, self).dispatch(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/views/generic/edit.py" in post
  183.             return self.form_valid(form)

File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/views.py" in form_valid
  119.         auth_login(self.request, form.get_user())

File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/__init__.py" in login
  161.     user_logged_in.send(sender=user.__class__, request=request, user=user)

File "/usr/local/lib/python3.6/site-packages/django/dispatch/dispatcher.py" in send
  193.             for receiver in self._live_receivers(sender)

File "/usr/local/lib/python3.6/site-packages/django/dispatch/dispatcher.py" in <listcomp>
  193.             for receiver in self._live_receivers(sender)

File "./card/models.py" in user_logged_in_callback
  75.     Profile.objects.filter(user=User).update(date_activation=datetime.now)

File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py" in filter
  787.         return self._filter_or_exclude(False, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py" in _filter_or_exclude
  805.             clone.query.add_q(Q(*args, **kwargs))

File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py" in add_q
  1250.         clause, _ = self._add_q(q_object, self.used_aliases)

File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py" in _add_q
  1276.                     allow_joins=allow_joins, split_subq=split_subq,

File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py" in build_filter
  1206.             condition = lookup_class(lhs, value)

File "/usr/local/lib/python3.6/site-packages/django/db/models/lookups.py" in __init__
  24.         self.rhs = self.get_prep_lookup()

File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py" in get_prep_lookup
  112.                 self.rhs = target_field.get_prep_value(self.rhs)

File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py" in get_prep_value
  966.         return int(value)

Exception Type: TypeError at /admin/login/
Exception Value: int() argument must be a string, a bytes-like object or a number, not 'ModelBase'


Michal Petrucha

unread,
Nov 9, 2018, 5:37:23 AM11/9/18
to Django users
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512

Found it. :) The error lies in the filter() call:

> @receiver(user_logged_in, sender=User)
> def user_logged_in_callback(sender, user, request, **kwargs):
> Profile.objects.filter(user=User).update(date_activation=datetime.now)

You're passing in the User class as the argument, rather than the
instance.

By the way, I suggest that you use django.utils.timezone.now() instead
of datetime.now; it's usually a good idea to use timezone-aware
timestamps. And side note, you need to call the function;
QuerySet.update doesn't accept callables.

Cheers,

Michal
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1

iQIcBAEBCgAGBQJb5WMVAAoJEHA7T/IPM/klwgkQAJpdDsTNeCFKnmcDpmXPs+S7
vQy+aEyaV3VkfgCpH92n/3Csvad5Fw4cloSef+4DIR1897Hj2x7ga8HA7chcPdJ5
g/mZQNti54ILJMOnWAISD5jPlikec9eibfs06PPSdJnz5O3fcN1hPAy5klWNyEDd
nL4u9IXqWeo8RtkPjKxLzm/im7QWLXYxPGtHnvQHpqHNQGvH0txfLHjUtCUvFV75
ZLPXDO1WUuVsX5T+JEJaLYy9L9TivE5QPwszBdG5pCVd3wJEgLgnkiWxLCbIKRNH
2+M+WQpQfJ2QgA9mOrxWXQaUQB/j8BNyJ1QqW/9F81TDzFjX4i4RIUy6myXrGTnY
l0yDE0O6tD3creuGYGmh9hJXXi/BWq39mkB/dCBSuHzA0qMc65g1UIS8plVCchMK
9djJwpwMo4uuWaQImUrN5d8lSlNDo7Hk5S4lGcGOyiAbuZ9qoSLDSRB0WFVouStW
3XU/9TU5u5FB/ay/oaZGE41V5y4NLpLNFQBtTowX6DQ2sj4d8H9xdFrms6mnwaJ3
+TPSalWERJ/oHGWp9or1kM+4/fYhku47ByteLcLWJM5sG+nF8omt+te+h5l/rVS9
COW8eFfAoMA2pf1ulIlpymEr8XsDJMAnJDF/5lo8GbDoo0g0IpIn0IzxB8KNqzAp
AUb68j4udCCpBCkgOZPB
=80IM
-----END PGP SIGNATURE-----

pastrufazio

unread,
Nov 9, 2018, 11:32:29 AM11/9/18
to Django users
Il giorno venerdì 9 novembre 2018 11:37:23 UTC+1, Michal Petrucha ha scritto:

Found it. :) The error lies in the filter() call:

Thank you very much. I fixed it using 

@receiver(user_logged_in, sender=User)
def user_logged_in_callback(sender, user, request, **kwargs):

   
Profile.objects.filter(user=user).exclude(date_activation__isnull=False).update(date_activation=datetime.now())

 
By the way, I suggest that you use django.utils.timezone.now() instead
of datetime.now; it's usually a good idea to use timezone-aware
timestamps. And side note, you need to call the function;
I will try it out, thanks.

QuerySet.update doesn't accept callables.
Sorry, what does it mean? 

Michal Petrucha

unread,
Nov 12, 2018, 7:21:00 AM11/12/18
to Django users
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512

Callables in Python are objects that you can call – typically a
function, but it can also be some other object that defines __call__.

Here I was just pointing out that your original code was
“.update(date_activation=datetime.now)”, meaning that you were passing
the function datetime.now to update, rather than the result of calling
it, and that wouldn't work. However, I can see that you fixed that in
your updated code, so nothing to see here. ;)

Michal
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1

iQIcBAEBCgAGBQJb6W/oAAoJEHA7T/IPM/klaRUP/3Jwvq9cCzzFL40pnZAZeGON
OeMxriJOnvLa/P3AiAa4cuUhqMmOnJDdWMGsozxVcY3QH7cQ0DgUVu1zl+ZZv0gj
ErPFzARvRaRhvfaYB01BhDRyj06Sgbufe20JmKqQDaUqo1ZcFEG4bEloq2Lp/Y6W
RcPLM/2Q4zH8AjfYD0F/RXFs4ktLVZ2esoOWtW8sqwFHAdOnB3hj1Kb1p8hPm5WD
ZZHrDkRajL/o0f1D29qQVXKoByQktWk0Gg47syztc1+CsdwmxDA6uwruHtajwILg
pQ84HnDy9YjoE1EAM9/DchjfrccrzZVUhtZtshAAvvEL90NpqDawepv+9Y2y6XZS
qS1cG0FTTyoRlVNBmSGbB1CxXy+26vFKKz56seorOUWS0vJ6OwoawMtngkoVEzU8
k8HDZ9iVbmtuY9TsjoDPfpfJJlZAEO45cay3Hu0Bm5ianon37sauagvS8RlHPSuB
V74hvySKLuaxHx0BShX+tHfOsXetFj+yEnNOCzKAps/Q1NlCE9NaHE43AmtUMlL/
+3LEM5LScg1HdGFufIsALf0cZi5hFCxEOoMFFGtcNETgw4Xhd+XAbqxf1a8EmhUT
gbTyS1aTrYhGr2ubpzIa5dE6UhlTsPA2AeAZCBt2DGvV8Ai7SvC7v6oYWGzPJFRX
8Ld48aT5Aa7U0NugUghn
=UII/
-----END PGP SIGNATURE-----
Reply all
Reply to author
Forward
0 new messages