Home > Mobile >  Why am I getting this Django custom command error: 'datetime.timezone' has no attribute &#
Why am I getting this Django custom command error: 'datetime.timezone' has no attribute &#

Time:11-03

Why am I getting the error "'datetime.timezone' has no attribute 'now'" when trying to run this custom command in Django that deletes guest accounts older than 30 days? It works elsewhere in views.py where I have imported it the same way. Do I have to import it differently since the command is in a different folder? (management/commands/)

from django.core.management.base import BaseCommand
from datetime import timezone, timedelta

from gridsquid.models import User, Tile

DEFAULT_TILE_IMG_NAME = "defaultsquid.svg"
MAX_GUEST_ACCOUNT_DAYS = 30

class Command(BaseCommand):
    def handle(self, *args, **options):
        """
        Deletes all guest user accounts and their media if older than MAX_GUEST_ACCOUNT_DAYS
        """
        # Get all guest accounts created before the limit
        expired_guests_count = User.objects.filter(guest=True).filter(date_joined__lt=timezone.now()-timedelta(days=MAX_GUEST_ACCOUNT_DAYS)).count()
        expired_guests = User.objects.filter(guest=True).filter(date_joined__lt=timezone.now()-timedelta(days=MAX_GUEST_ACCOUNT_DAYS))
        
        for guest in expired_guests:
            tiles = Tile.objects.select_related("user").filter(user=guest).all()
            for tile in tiles:
                # Delete image if not default image
                if DEFAULT_TILE_IMG_NAME not in tile.image.url:
                    tile.image.delete()
                # Delete audio file if there is one
                if tile.audio is not None:
                    tile.audio.delete()
            # Delete guest account
            guest.delete()

CodePudding user response:

Change imports to this:

from django.utils import timezone
from datetime import timedelta

And it will work better. Django also uses datetime.

CodePudding user response:

from django.utils import timezone

You need to import it like this, this is the doc

  • Related