【问题标题】:How to acces a non returned CharField from models in my views?如何从我的视图中的模型访问未返回的 CharField?
【发布时间】:2018-12-24 00:10:04
【问题描述】:

在开始之前,我想澄清一下我是 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

这是我的观点.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/ 页面。到目前为止,我了解,我可以在我的 models.py 中添加 details_note 到返回值中。但我不知道如何真正做到这一点,我知道我不能只做return self.title_of_note, self.details_note

如何在我的views.py 中访问details_note

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

我的索引模板

<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>

【问题讨论】:

  • 出于好奇,您能否将您的模板也添加到问题中?
  • 我没想到。现在就做。

标签: python django python-3.x django-models django-views


【解决方案1】:

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

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 }}

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

【讨论】:

  • 非常感谢。它完全按照我的意愿工作。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
  • 2014-04-19
  • 1970-01-01
相关资源
最近更新 更多