Upload imagefield Django

121 Views Asked by At

I need help please. I want to upload my images but there's a problem A screenshot of what I get I uploaded my images dynamically, In the model I have:

....
class Visage(models.Model):
    personne = models.ForeignKey(Personne)

    def generate_filename(self, filename):
        return "personne/static/personne/Images/%s/%s"% (self.personne.nom,filename)

    image = models.ImageField(blank=False, upload_to=generate_filename)
    ...

In the template I have:

{% for image in visages_liste %}
        <a href="{{image.image.url }}"> <img src="{{image.image.url}}" height="420"></a>
    {% endfor %} 

the url of the image looks like: localhost:8000/personne/static/personne/Images/NameOfThePerson/NameOfTheImage.jpg

The view :

class IndexView (generic.ListView):
    template_name = 'personne/accueil.html'
    context_object_name = 'visages_liste'


    def get_queryset(self):
        return Visage.objects.all()

In the urls I've tried so many different things but no one worked. What do I should put in the STATIC_MEDIA and the STATIC_URL ? and what to put in the urls to work ?

2

There are 2 best solutions below

1
Curtis Olson On BEST ANSWER

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}))
9
Leonard2 On

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.