python - 如何在我的视图中从模型中访问未返回的 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>
解决方案
您需要将您的笔记传递给模板。
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
上下文变量以供在模板中使用。
推荐阅读
- python - 我在 .csv 文件的特定列中有 MongoDB 格式的字符串行 如何将其转换为数据框?
- java - JavaCC 中 JAVA_UNICODE_ESCAPE 的作用是什么?
- python - 修复 IndexError:列出超出范围的问题
- java - 在 Spring Boot 和 Thymeleaf 中解析模板名称时出错
- r-markdown - xaringan都会主题幻灯片标题字体大小
- c# - JsonSerializationException 解析
- javascript - Javascript将文件从网页上传到特定的谷歌驱动器帐户
- php - 我使用 netbeans,我想运行我的 PHP 应用程序,我已经在我的机器上安装了 xampp 和 wampserver
- python - 使用套接字在python中发送数据
- java - 在 JPA 中对具有多对多关系的对象执行 NOT IN QUERY