简体   繁体   中英

Displaying images in html - Django

I have a little problem, and I dont have idea why my project doesn't work how I want. I have a models.py

class Strona(models.Model):
    title = models.CharField(max_length=250, verbose_name="Tytuł", help_text="Podaj tytuł artykułu")
    slug = models.SlugField(unique=True, verbose_name="Adres url SEO", help_text="Automatycznie tworzony przyjazny adres URL")
    content = HTMLField(verbose_name="Treść artykułu", help_text="Wypełnij treścią artykułu")
    image = models.FileField(upload_to='blog_images',verbose_name="Obrazek", help_text="Załącz obraz")

and in view.py I have

from django.shortcuts import render
from .models import Strona

def strona_glowna(request):
    strona_glowna = Strona.objects.all()
    context = {'strona_glowna': strona_glowna}
    return render(request, 'strona/index.html', context=context)

After that I've create the html file and include inside a code :

...
    {% for strona in strona_glowna %}
    <strong>{{strona.title}}</strong><br>
    {% if strona.image == True %}
    <img src="{{strona.image.url}}"><br>
    {% else %}
    {% endif %}
    <p>{{strona.content|safe}}<p></p>
    {% endfor %}    
...

in setting.py I declared:

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

And the problem is, when I reload a website the images doesn't show. I think the routing for upload is ok, but I don't know why I can't display the images. Any ideas?

Updated

在此处输入图片说明

EDIT:

When I added in myapp/urls.py the code:

from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from . import views


urlpatterns = [
    path('', views.strona_glowna, name="strona_glowna"),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_ROOT, document_root=settings.MEDIA_ROOT)

and set in setting.py the code:

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
ENV_PATH = os.path.abspath(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(ENV_PATH, '/static/') 
MEDIA_ROOT = os.path.join(ENV_PATH, '/media/') 
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

the django responde me a error:

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/media/images/allmini.jpg
Using the URLconf defined in moja.urls, Django tried these URL patterns, in this order:

admin/
[name='strona_glowna']
^static\/(?P<path>.*)$
^D\:\/media\/(?P<path>.*)$
tinymce/
The current path, media/images/allmini.jpg, didn't match any of these.

Mayby You know where is a bug - I can't find it... In google chrome inspector the path is :

<img src="images/allmini.jpg">

If you don't have {% load static %} add it on top of your html file, then in your settings.py add the MEDIA_ROOT with the full path to your media folder, for example this is my MEDIA_ROOT :

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images/')

And this is my MEDIA_URL :

MEDIA_URL = '/'

EDIT:

the field in my model:

profile_picture = models.ImageField(
    upload_to=get_user_upload_path, default=os.path.join(settings.MEDIA_ROOT, "profile_picture.png"),
    blank=True, null=True
)

the method for uploading the image to the field:

def get_user_upload_path(instance, filename):
    """ Crea il percorso ed il nome del file per l'upload. """
    # Recupero l'estensione dell'immagine.
    extension = filename.split('.')[-1]
    filename_no_ext = "%s_%s_%s_%s" % ('img', instance.first_name, instance.last_name, instance.pk)
    filename = "%s_%s_%s_%s.%s" % ('img', instance.first_name, instance.last_name, instance.pk, extension)
    # Elimino la vecchia immagine del profilo.
    try:
        os.remove(os.path.join(settings.MEDIA_ROOT, "users/", "%s.%s" % (filename_no_ext, "jpg")))
    except OSError:
        pass
    try:
        os.remove(os.path.join(settings.MEDIA_ROOT, "users/", "%s.%s" % (filename_no_ext, "jpeg")))
    except OSError:
        pass
    try:
        os.remove(os.path.join(settings.MEDIA_ROOT, "users/", "%s.%s" % (filename_no_ext, "png")))
    except OSError:
        pass
    # Ritorno il percorso completo del file.
    return os.path.join(settings.MEDIA_ROOT, "users/", filename)

Like this the user profile image will be save in projectname/static/images/users/filename

EDIT:

If you don't have it add this to your urls.py:

urlpatterns = [
    ...
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_ROOT, document_root=settings.MEDIA_ROOT)

To access the image in template use:

{{ strona.image }}. strona.image would not have a key named url .

Note : strona.image value would be a URL itself. You can check that by printing it in a different tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM