Trollgon
Trollgon

Reputation: 65

Django: ImageField sets wrong url

I am new to django and set up my first project with one app in the beginning. Some time later I figured out that I need a custom user model so I've created a second app with the custom user model as I've read somewhere that you need the user model as first migration (I'm telling this, because I believe my project structure is causing my problem).

Right now I am working on an avatar upload for the user model. I am able to upload an image via DRF and then open the image in my browser, but not with the saved url in my database.

Django saves the image like this in the database: http://localhost:8000/api/users/<user_id>/media/avatars/image.jpg. But the correct url would be: http://localhost:8000/media/avatars/image.jpg

How do I make django save the correct url?

I've set MEDIA_ROOT and MEDIA_URL like this:

MEDIA_ROOT = BASE_DIR + 'media'
MEDIA_URL = 'media/'

My project structure:

my project
- backend (first app)
- - manage.py
- - settings.py
- users (second app)
- - models.py # here is my custom user model

The custom user model:

class User(AbstractBaseUser, PermissionsMixin):
    username_validator = UnicodeUsernameValidator()

    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    email = models.EmailField(_('email address'), unique=True)
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin site.'),
    )
    date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )
    avatar = models.ImageField(
        upload_to='avatars/',
        null=True,
        blank=True
    )

    objects = UserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    class Meta:
        db_table = 'auth_user'
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this user."""
        send_mail(subject, message, from_email, [self.email], **kwargs)

Any help is appreciated

Upvotes: 1

Views: 517

Answers (1)

mtoy
mtoy

Reputation: 195

Try change your settings.py to absolute paths:

MEDIA_ROOT = '/var/www/your_project_path/media/'
MEDIA_URL = '/media/'

Remember about slashes / /

Upvotes: 1

Related Questions