petru
petru

Reputation: 15

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

Upvotes: 1

Views: 111

Answers (2)

Hybrid
Hybrid

Reputation: 7049

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)

Upvotes: 1

doniyor
doniyor

Reputation: 37846

I dont know how your MEDIA_URL looks like but the media settings should look like something like this:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

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

and no, you do not save media files under templates folder. this does not make any sense. templates should have html files, static should have static files (css, js, static images) and media user uploaded files.

this way, if someone joins your project or your project gets bigger, you dont end up in chaos/misleading folder names, otherwise it really hurts, believe me

For 404 issue:

you need change your main urls.py in root to include this:

if settings.DEBUG:
    urlpatterns += patterns('',
       url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
       {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
    url(r'', include('django.contrib.staticfiles.urls')),
)

Upvotes: 1

Related Questions