Nicolás Curti Nicolás Curti - 1 year ago 73
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')


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 Source

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

Add this to your

DEBUG = True

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

    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

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download