As stated above, to be able to upload the image, its url needs to be correct which implies you have a static file server.
The best way to do this would be to use a Imagefield, and configuring the MEDIA_URL and the MEDIA_ROT in the py Settings. of the project and then include this url in the py. of the project.
see how to serve static files on Django here Django-2.0-files
For a Imagefield make the following settings and this works perfectly:
Adds the MEDIA_ROT and MEDIA_URL in the py Settings.
# projeto/settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# projeto/urls.py
from django.conf import settings
from django.conf.urls import url
from django.contrib import admin
from django.urls import path, include
from django.views.static import serve
urlpatterns = [
path('admin/', admin.site.urls),
# incluir noticias.urls
path('noticias/', include('noticias.urls')),
# caminho para servir arquivos
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
]
# noticiasapp/models.py
from django.db import models
class Noticia(models.Model):
titulo = models.CharField(max_length=200)
imagem = models.ImageField(upload_to="media/images/noticias")
texto = models.TextField()
# noticiasapp/urls.py
urlpatterns = [
path('', views.listar_noticias, name="listar_noticias")
]
# noticiasapp/views.py
from django.shortcuts import render
from .models import Noticia
def listar_noticias(request):
context = {'noticias': Noticia.objects.all()}
return render(request, 'noticias/listar_noticias.html', context)
noticiasapp/templates/noticiasapp/listar_noticias.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Noticias</title>
</head>
<body>
<ul>
{% if noticias.count > 0 %}
{% for noticia in noticias %}
<li>
<h3>{{ noticia.titulo }}</h3>
<p>{{ noticia.texto }}</p>
<img src="{{ noticia.imagem.url }}">
</li>
{% endfor %}
{% else %}
<h3>Sem notícias ainda</h3>
{% endif %}
</ul>
</body>
</html>
Thank you very much! It worked correctly.
– Gustavo Augusto Pires