I want to delete users that haven't activated their accounts when the activation token have expired, activation token expires after 30 minutes.
from django.db.models.functions import Now
def delete_unactivated_users():
User = get_user_model()
expiry = User.date_joined timedelta(seconds=1800)
unactivated_users = User.objects.filter(Q(Now()__gt=expiry) & (Q(is_active = False)))
for user in unactivated_users:
user.delete()
print('<<<User Deleted>>>')
user.save
I am getting a syntax error on line 5 of the code, I tried using
unactivated_users = User.objects.filter(Q(expiry__lt=Now()) & (Q(is_active=False)))
but it didn't result in the same meaning. The problem seems to be the placing of Now()
and expiry
on line 5
CodePudding user response:
As I understood you want to delete inactive users, more specifically those which have is_active=False
and date_joined 30 minutes is less than Now()
. If that's true here is how you can do that.
from django.utils import timezone
def delete_inactive_users():
User = get_user_model()
inactive_users = User.objects.filter(
date_joined__lt=timezone.now() - timezone.timedelta(seconds=1800),
is_active=False,
)
# you can delete all the records by once
inactive_users.delete()
CodePudding user response:
Without seeing your full error I can't be certain, but there are definitely a few things wrong:
You don't need to save the user after deleting it (in fact you won't be able to as it won't exist) - you can also delete the whole list at once.
You don't need Q
The Now
you are importing isn't correct
This should work:
from django.utils.timezone import now
def delete_unactivated_users(expiry_time):
User = get_user_model()
expiry = User.date_joined timedelta(seconds=1800)
unactivated_users = User.objects.filter(expiry__lt=now(), is_active = False)
unactivated_users.delete()