djangoimagedjango-urlsmedia-url

Upload imagefield Django


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 ?


Solution

  • 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}))