首页 > 解决方案 > 如何在我的视图中从模型中访问未返回的 CharField?

问题描述

在开始之前,我想澄清一下我是 django 的初学者,所以我正在学习..

这是我的models.py

    class MyNote(models.Model):
         title_of_note = models.CharField(max_length=200)
         date_created = models.DateTimeField('Created')
         details_note = models.TextField(max_length=2500, default="")
         def __str__(self):
             return self.title_of_note

这是我的views.py

def index(request):
    notes_list = MyNote.objects.order_by('date_created')
    context  = {'notes_list' : notes_list}
    return render(request, 'note/index.html', context)

def detail(request, note_id):
    note = get_object_or_404(MyNote, pk=note_id)
    return render(request, 'note/detail.html', {'request' : note})

我的目标是有一个主页 /note/ ,我可以从我的所有笔记中选择title_of_note. 在我选择其中一个笔记并单击指向一个 (/note/1/) 的链接后,它会将我显示title_of_note为标题,在标题下方,我可以看到我的详细信息details_note。到现在为止,我设法用笔记的标题作为链接做主页,按创建日期排序。一切正常,但我不知道如何将标题下的详细信息添加到 /note/1/ 页面。到目前为止,我了解,我可以details_note在我的 models.py 中添加回报。但我不知道如何真正做到这一点,我知道我不能只是这样做return self.title_of_note, self.details_note

如何访问details_note我的 views.py ?

我真的没有想法,希望能得到一些帮助。这是我在这里的第一个问题,所以如果我做错了什么,我很抱歉。

我的索引模板

<body bgcolor="black">
<p><font size="5", color="white">You are at the main page of my notes.</p>
{% if notes_list %}
    <ul>
    {% for note in notes_list %}
        <li><font size="3", color="white"><a href="{% url 'note:detail' note.id %}">{{ note.title_of_note }}</a></font></li>
    {% endfor %}
    </ul>
{% else %}
    <p><font size="5", color="white">There was a problem. Probably no notes</font></p>
{% endif %}
</body>

这是我的详细模板

<body bgcolor="black">
    <h1><font size="5", color="white">{{ note.title_of_note }}</font></h1>
    <p><font size="3", color="pink">{{ note.details_note }}</font></p>
</body>

标签: pythondjangopython-3.xdjango-modelsdjango-views

解决方案


您需要将您的笔记传递给模板。

def detail(request, note_id):
    note = get_object_or_404(MyNote, pk=note_id)
    context = {'note': note}
    return render(request, 'note/detail.html', context)

在模板中,您可以像这样从注释中获取信息:{{ note.title_of_note }}{{ note.details_note }}

在您的代码中,您正在request用实例覆盖上下文变量note,不要这样做,因为 Django 将添加一个request上下文变量以供在模板中使用。


推荐阅读