Images with Django - exhibition and Static

Asked

Viewed 3,598 times

1

I’m a beginner in Django and I’m developing a simple blog.


I know that the configuration of static files needs to be different for the development and production environment, but I always get caught up in understanding how it works since I never deploy any web application and I don’t know how the server handles the files.

If someone has any indication of reading so that I understand better how this works would be of great help.

Keeping this in mind, I am developing the blog in development environment and I came across the following problem:

Within the 'models' of a given application there is a field Filefield who is responsible for handling the import of the blog post header image.

content.models.py

from django.db import models
from tinymce import models as tinymce_models


class Article(models.Model):
    titulo = models.CharField(max_length=200)
    photo = models.FileField(upload_to='static', null=True, blank=True) 
    autor = models.CharField(max_length=30)
    corpo = tinymce_models.HTMLField(null=True, blank=True) #Tinymce field
    data = models.DateField()
    tag = models.CharField(max_length=30)
    .
    .
    .

This file is collected in my view:

content.views.py

def home (request):
menu = Article.objects.all()
lista_artigos = Article.objects.all() 
paginator = Paginator(lista_artigos, 2) 
trabalhos_feitos = Work.objects.all() 

page = request.GET.get('page')  
try:
    conteudo = paginator.page(page)
except PageNotAnInteger:
    conteudo = paginator.page(1)
except EmptyPage:
    conteudo = paginator.page(paginator.num_pages)

context = {'conteudo_artigo': conteudo, 'menu':menu,'trabalhos':trabalhos_feitos}
return render(request, 'base.html', context)

And passed to my template:

html base.

{% for item in conteudo_artigo%}
{% if item.photo %}
    <img src="{{item.photo}}" class="img-responsive" alt="...">
{% endif %}

    <a id='titulo' href="/artigos/{{item.id}}">{{item.titulo}}</a>
    <h5 id ='autor'>{{item.autor}}</h5>
    <h5 id ='tag'>{{item.tag}}</h5>

    {% if item.corpo|length > 1000 %} 
        <p id = 'corpo_artigo'>{{item.corpo|truncatewords:200|safe}} </p> 
        <h5 id ='data'>{{item.data}}</h5>
        <button class="btn btn-default navbar-btn"> <a href="/artigos/{{item.id}}">Continue Lendo</a></button>
    {% else %}
        <p>{{item.corpo|safe}} </p>
        <h5 id ='data'>{{item.data}}</h5>
    {% endif%}      
 {% endfor %}

So far so good. The image (even Filefield is not ideal for dealing with images) usually appears in my layout.

inserir a descrição da imagem aqui

The problem is that I have another function in my view that is responsible for directing to a page containing only the article. When this is done, the image ceases to appear.

content.views.py

def artigos(request,id_pagina_artigo): 
menu = Article.objects.all() 
try:
    materia = Article.objects.get(id=id_pagina_artigo)
except ObjectDoesNotExist:
    #raise Http404
    return render(request, '404.html', {'menu':menu})

return render(request, 'artigo.html', {'teste': materia, 'menu':menu})

inserir a descrição da imagem aqui

This is the template configuration for this view function:

{% extends "index.html"%}
{% load static %}
{% block artigo_full %}

<div class='row'>
     <div id='artigo' class='col-lg-12 col-md-12 col-sm-12'>
         {% if teste.photo %}
             <img src="{% static '{{teste.photo}}' %}" class="img-responsive" alt="...">
         {% endif %}
         <a id='titulo' href="/artigos/{{teste.id}}">{{teste.titulo}}</a>
         <h5 id ='autor'>{{teste.autor}}</h5>
         <h5 id ='tag'>{{teste.tag}}</h5>
         <p>{{teste.corpo|safe}} </p>
         <h5 id ='data'>{{teste.data}}</h5>
     </div>
 </div>

{% endblock %}

I know that much that is shown in the code is not the most efficient and has a lot of hardcoded stuff, but take into account that I am beginner and that my intention is to build the base structure and go deeper into the code to improve its syntax.

At last, my py.url:

from content import views
from django.contrib import admin
from django.conf.urls import url , include

urlpatterns = [
    url(r'^$', views.home),
    url(r'^artigos/(?P<id_pagina_artigo>\d+)$', views.artigos),
    url(r'^portfolio/$', views.portfolio),
]

2 answers

1


I believe the problem is the way you are trying to render the file path. In the listing you do so:

<img src="{{item.photo}}" class="img-responsive" alt="...">

And on the Detail page you do so:

<img src="{% static '{{teste.photo}}' %}" class="img-responsive" alt="...">

I’m a little rusty on Django, but I don’t think he’s going to be able to render a variable inside a tag template. So my suggestion would be you standardize the use for the first way you used.

  • When I standardize to be equal to the first option the image is not yet shown and the following error is shown in the terminal: Not Found: /artigos/Static/imagem3_FcljUkP.jpg Ie , it seems that without using Static it tries to fetch the file in another folder.

  • Oh yes, well remembered. For you to serve files "uploaded" by the user, you have to add a hack in your urls.py. Here’s the thing you’ve probably seen: Django wasn’t meant to serve files, but for the development environment, that’s fine. Look at this link how to do.

-1

In my case the image was not appearing in the test environment precisely because of the different way that static objects are treated, so I needed to add the following line in my Settings:

MEDIA_URL = '/media/'

Where the folder media is created to store image files like yours and is in my main application folder.

After that a new URL was included only for the test environment in the.py urls file as below:

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

These two programs solved the presentation of the images in my tests.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.