pythondjangomediamedia-url

django - why is this not working?


i have this image field in my model

foto = models.ImageField(upload_to="user/%Y/%m/%d",default='')

and in my settings:

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

and in my template:

<img class="profilfoto" src="{{MEDIA_URL|escapejs}}{{user.foto.name}}" />

other images with upload_to='.' are being saved right into media folder, but user folder isnot being created, why is this?

i ran syncdb and schemamigration, everything works fine but loading this image is giving 404 error as the path isnot there. what can be my mistake?


Solution

  • escapejs

    Escapes characters for use in JavaScript strings. This does not make the string safe for use in HTML, but does protect you from syntax errors when using templates to generate JavaScript/JSON.

    <img class="profilfoto" src="{{MEDIA_URL|escapejs}}{{user.foto.name}}" />
    

    Your above code results to, for example: user/2013\u002D04\u002D10_170411/image.png, which giving you 404 error while loading this image.

    UPDATE:

    when you save or update an image, you must define the enctype in the form. This will allow you to save an image or a file:

    <form id="registerform" action="/angemeldet/" method="post" 
        enctype="multipart/form-data">
        {% csrf_token %}
    

    AND

    form = YourForm(request.POST, request.FILES)
        if form.is_valid():