简体   繁体   English

Django 2.1-无法在html文件中链接我的模型变量

[英]Django 2.1 - can't link my models variables in html file

guys, first of all thanks for your time. 伙计们,首先感谢您的宝贵时间。 im 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. 我在我的应用程序的index.html上在django 2.1中设计模板文件时遇到一些问题,我可以进入详细信息页面,尽管当我想在html文件中设计我的详细信息页面时,我放置了引用,但浏览器给了我没有。 MY MODELS.PY from django.db import models django.db的MY MODELS.PY导入模型

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 Wich (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, Wich
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 我的detail.html文件

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

but the only thing that i get is the 'titulo' in . 但是我唯一得到的是中的“ titulo”。 i've tried to create variables in views for 'imagem' and 'make' and got nothing. 我试图在“ imagem”和“ make”的视图中创建变量,但一无所获。 again thanks for your time. 再次感谢您的宝贵时间。

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. 我以某种方式更改了detail视图,使您在模板中访问变量时更有意义。

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 }} . 现在,您可以使用{{ dream.titulo }}{{ 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. 要访问引用的Wich对象,您必须知道Django通过向引用的模型添加属性<model>_set来自动创建反向关系 In your case dream.wich_set . 在你的情况下dream.wich_set This is an instance of a RelatedManager and provides methods like .filter() , .all() , ... for fetching the objects from the database. 这是RelatedManager的实例,并提供.filter() .all() ,...之类的方法,用于从数据库中获取对象。

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 这就是为什么我们得到多个结果,并且必须使用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. 另外,我建议使用ImageField而不是CharField来存储图像。 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. 存储在ImageField中的每个图像(从FileField继承所有方法和属性)都具有url属性,该属性适用于img标签的src属性。 <img src="{{ dream.imagem.url}}"> . <img src="{{ dream.imagem.url}}">

At first I will suggest to use get_object_or_404() instead of try, except. 首先,我建议使用get_object_or_404()代替try,除非。 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 . 如果要访问模板中的任何变量,则应该并且必须通过context发送它。 You are sending dream object in the form of titulo variable in context so to access image field you have to use 您正在以上下文变量titulo的形式发送梦想对象,因此您必须使用访问图像字段

<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. 就像您要在模板中使用wich ,您还必须确保要使用哪个wich ,并通过视图从上下文发送它,或者必须使用titulo.wich_set.all访问与梦境对象(titulo)相关的所有wich ,这将返回所有与dream(tutilo)对象有关的所有内容,然后可以循环访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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