[Fixed]-Upload imagefield Django

0👍

In settings.py, try setting your MEDIA_ROOT to:

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

And in your project’s urls.py file add:

from django.conf import settings
from django.conf.urls import patterns

# Add this to the end of the urls.py file, after your other urls
if settings.DEBUG:
    urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}))

1👍

upload_to of ImageField needs to be the subroot after settings.MEDIA_ROOT.

Instead of

ImageField(blank=False, upload_to=os.path.join(MEDIA_ROOT, 'personee'))

please try

ImageField(blank=False, upload_to='personne')

then the image will be save in MEDIA_ROOT/personne.

EDIT:
with your model setting,

Instead of

def generate_filename(self, filename):
    return os.path.abspath(os.path.join(MEDIA_ROOT, 'personne/static/personne/Images/'))+'/' + self.personne.nom+'/'+ filename

please try

def generate_filename(self):
    return 'personne/static/personne/Images/'+self.personne.nom

then the image will be uploaded in MEDIA_ROOT/personne/static/… as specified.

Leave a comment