python - 如何从Django中的数据库中获取另一个应用程序的值?
问题描述
如何从另一个应用程序获取值并在 Django 项目的另一个应用程序中存在的模板中显示该值?我有这个项目目录结构: -
-News-Scrape
- accounts
- education
- home
- news
- models.py(The value is present here)
- views.py
- templates
- static
- templates
- base.html(I want to display a value here which is present in the `news` app)
由于base.html
文件不在应用程序中,我如何news
在此页面中显示应用程序数据库中的任何特定值。
这是models.py
(来自新闻应用程序)文件:-
from django.db import models
class PageView(models.Model):
hits = models.IntegerField(default=0) #I need this value to be displayed in my `base.html` file
这是views.py
(来自新闻应用程序)文件:-
def news_list(request, *args, **kwargs):
if(PageView.objects.count()<=0):
x=PageView.objects.create()
x.save()
else:
x=PageView.objects.all()[0]
x.hits=x.hits+1
x.save()
context={}
context = {
'object_list': queryset,
'page': x.hits
}
return render(request, 'news_list.html', context)
如果base.html
文件在news
应用程序内部,我可以轻松地通过 获取值,但是当文件存在于应用程序外部{{object.<id_label>}}
时,这不起作用。base.html
我是 Django 的初学者,很难找到实现这一目标的方法。
解决方案
新闻-刮
accounts
education
home
news
templates
news
base.html
或您的 html 文件models.py
views.py
您可以为项目中的每个应用程序创建单独的模板文件夹
推荐阅读
- c# - 摆脱“正在构建的项目的处理器架构之间的不匹配”“MSIL”
- easy68k - 如何在 EASy68k 中显示任务 #8?
- api - 命名 REST API - 获取非成员属性的集合
- python - 有条件地从熊猫数据框中删除行
- javascript - 具有高级公共/令牌规则和数组包含的 Firestore 安全规则
- python - Flask 中的 count() 与 count = count + 1
- swift - 在 macOS 上使用 swiftUI 实现 webkit(并创建网页的预览)
- android - 在recyclerview中删除项目后我的数据返回
- lua - 尝试使用“findFirstChild”错误索引 nil
- javascript - .appendChild 不是 HTMLButtonElement 中的函数。在 DOM 中