Nicolás Curti Nicolás Curti - 5 months ago 17
Python Question

Saving an image into user model

I'm trying to make an "avatar" field in my user model (tried using all libraries out there, didnt quite like them)

class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
...
pic = models.ImageField(upload_to="photos", default='pic')


in setting.py

MEDIA_ROOT = '/media/'


Also I'm not even using a form but uploading directly from the admin, the problem is that the image does not save into the folder templates/media/photos.

Also I dont have any view associated, just trying the image to save into the folder so I can understand better how the file system works.

edit: misspelled

Answer

You need to configure your settings to serve static media properly when using a local environment.

Add this to your settings.py

DEBUG = True

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'

Add this to your ROOT urls.py

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.conf.urls.static import static


if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)