Django 2.1 – can't link my models variables in html file

Question:

I’m having some problems to design my templates files in Django 2.1
at the index.html of my app I can get in at the details page although when I want to design my detail page in the html file I put the references but the browser gives me nothing.

MY MODELS.PY
from django.db import models

class Dreams (models.Model):
    titulo = models.CharField(max_length=100)
    objetivo = models.CharField(max_length=100)
    imagem = models.CharField(max_length=100)

    def __str__(self):
        return self.titulo + ' - ' + self.objetivo


class Wish (models.Model):
    lets = models.ForeignKey(Dreams, on_delete=models.CASCADE)
    make = models.CharField(max_length=100)
    it = models.CharField(max_length=100)

    def __str__(self):
        return self.make

MY VIEWS.PY

from django.http import HttpResponse, Http404
from .models import Dreams, Wish
from django.template import loader
from django.shortcuts import render


def index(request):
    all_dreams = Dreams.objects.all()
    contexto = {'all_dreams': all_dreams}
    return render(request, 'index.html', contexto)


def detail(request, Dreams_id):
    try:
        titulo = Dreams.objects.get(pk=Dreams_id)
        contexto = {'titulo': titulo}
    except Dreams.DoesNotExist:
        raise Http404("sem sonhos")
    return render(request, 'detail.html', contexto)

MY detail.html FILE

<img src = {{ dreams.imagem }}>
<h2>{{ titulo }}</h2>
<h3>{{ wish.make }}</h3>

but the only thing that I get is the ‘titulo’ in <h2>. I’ve tried to create variables in views for ‘imagem’ and ‘make’ and got nothing.
again thanks for your time.

Asked By: lucasrf27

||

Answers:

Your solution is almost correct, you just misused the objects in your template. If you pass an object to your template you can access its attributes by using the . notation. I changed your detail view in a way, that the variables make more sense when you access them in the template.

def detail(request, Dreams_id):
    try:
        dream = Dreams.objects.get(pk=Dreams_id)
        contexto = {'dream': dream}
    except Dreams.DoesNotExist:
        raise Http404("sem sonhos")
    return render(request, 'detail.html', contexto)

You can now access the title and the image by using {{ dream.titulo }} and {{ dream.imagem }}.

<img src="{{ dream.imagem }}">
<h2>{{ dream.titulo }}</h2>

To access your referenced Wich objects, you have to know that Django automatically creates a reverse relation by adding an attribute <model>_set to the referenced model. In your case dream.wich_set. This is an instance of a RelatedManager and provides methods like .filter(), .all(), … for fetching the objects from the database.

This reverse relation is a One-To-Many relation. That is why we are getting multiple results and have to iterate over them in the template using a for-loop

<img src="{{ dream.imagem }}">
<h2>{{ dream.titulo }}</h2>
{% for wich in dream.wich_set.all %}
    <h3>{{ wich.make }}</h3>
{% endfor %}

Additionally I would recommend using an ImageField instead of a CharField to store your image. Each image stored in an ImageField (which inherits all methods and attributes from the FileField) has an url attribute, which is suitable for the src attribute of an img tag, eg. <img src="{{ dream.imagem.url}}">.

Answered By: escaped

At first I will suggest to use get_object_or_404() instead of try, except.
Now let me come to the main point. If you want to access any variable in template the you should and you must send it through context. You are sending dream object in the form of titulo variable in context so to access image field you have to use

<img src = {{ titulo.imagem }}>

instead of

<img src = {{ dreams.imagem }}>

As well as if you want to use wich in template the you have to make sure you want which wich and send it via context from view or have to access all wich related to the dreams object(titulo) using titulo.wich_set.all which will return you all the wich related to the dream(tutilo) object and you can loop through it.

Answered By: Sam