Home > Mobile >  Django ImageField get username
Django ImageField get username

Time:12-05

models.py

   def upload_to(instance, filename):
        return 'verify/%s/%s' % (instance.user_idx.username, 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'

This is my model. but It is showed me error.

account.models.UserVerifyImg.user_idx.RelatedObjectDoesNotExist: UserVerifyImg has no user_idx.

I don't now what is the problem. help me please.

CodePudding user response:

Have you run migrations after changing in your model?

python manage.py makemigrations

Then:

python manage.py migrate

CodePudding user response:

You are actually using the right query instance.user_idx.username the problem is that at the time you assigning the image path(upload_to) the instance is not created,so that means you can not get instance.user_idx.username that is why you are getting that exception.
To solve this problem you can create a foreignkey by doing something like this.

class UserVerifyImg(models.Model):
    user_idx = models.ForeignKey(
                User,
                db_column='user_idx',
                on_delete=models.CASCADE
          )
    business_type = models.CharField(max_length=255)
    upload_date = models.DateTimeField(auto_now = True)
        
    class Meta:
        managed = False
        db_table = 'account_user_verify'


def upload_to(instance, filename):
    return 'verify/%s/%s' % (instance.user_verify_img.user_idx.username, filename)

class Image(models.Model):
    user_verify_img = models.ForeignKey(UserVerifyImg,on_delete=models.CASCADE)
    image = models.ImageField(upload_to=upload_to)
  1. run python manage.py makemigrations
  2. run python manage.py migrate

Note that You have to change your form and your views for this to work if you need more help let me know

  • Related