Home > database >  How to get username in models.py?
How to get username in models.py?

Time:12-04

models.py

def upload_to(instance, filename):
    nowDate = datetime.now().strftime("%Y/%m/%d")
    return '/'.join(['verify', UserVerifyImg.user_idx.username, nowDate, filename])

class UserVerifyImg(models.Model):
    user_idx = models.ForeignKey(
        User,
        db_column='user_idx',
        on_delete=models.CASCADE
  )
    business_type = models.CharField(max_length=255)
    image = models.ImageField(upload_to=upload_to)
    upload_date = models.DateTimeField(auto_now = True)

    class Meta:
        managed = False
        db_table = 'account_user_verify'

I searched about instance.user.username but It is showed errer.

AttributeError: 'UserVerifyImg' object has no attribute 'user'

This is my error.

CodePudding user response:

you can do something like this to get the username

instance.user_idx.username

CodePudding user response:

Hello you should use UserVerifyImg.user_idx.username in your views,
and in the upload_to() function, you should use instance.user_idx.username

Note: I have edited my code following your edit

  • Related