我有一个名为 Project_Name 的项目和一个名为 first_app 的应用程序,其中包含一些文章。 我在我的主页上显示这些文章标题作为应用程序页面上文章的链接。
所以在 127.0.0.1:8000/
我有 index.html。在这里我显示文章列表。然后,如果我点击一篇文章,我会转到 127.0.0.1:8000/first_app/1
,例如显示第一篇文章。
这是我的项目范围的 views.py:
...
from first_app.models import Article
def home(request):
latest_article_list = Article.objects.order_by('-pub_date')[:20]
context = {'latest_article_list': latest_article_list}
return render(request, 'index.html', context)
在我的项目范围内的 urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'Project_Name.views.home', name='home'),
url(r'^admin/', include(admin.site.urls)),
...
这是我的 first_app 应用程序中的 models.py:
from django.db import models
from datetime import datetime
class Article(models.Model):
name = models.CharField(max_length=140)
content = models.CharField(max_length=1000)
pub_date = models.DateTimeField(default=datetime.now())
这是我的 first_app 应用程序中的 views.py:
def article_detail(request, article_id):
art = get_object_or_404(Article, pk=article_id)
return render(request, 'first_app/detail.html', {'article': art})
这是我的 first_app 模板文件夹中的 detail.html:
<h2><u>{{ article.name }}</u></h2>
<b>Published On: </b>{{article.pub_date }}
<b>Content: </b>
<ul>
<li>{{ article.content }}</li>
</ul>
这是我的项目主页,index.html:
{% if latest_article_list %}
<h2>Latest Articles</h2>
<ul>
{% for article in latest_article_list %}
<li><a href="/first_app/{{ article.id }}/">{{article.name }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No articles are available.</p>
{% endif %}
一切正常。
我的问题: 如果我有两个或更多应用程序,每个应用程序都有自己的文章(出于其他原因,我将不同应用程序的文章分开),我将如何在主页上获得这些文章?然后我将如何构建 URL,以便当我从主页点击一篇文章时它会将我带到正确的应用程序 URL?
例如,我有应用程序:first_app、second_app 和 third_app。每个应用程序中都有几篇文章。我希望我的主页显示来自每个应用程序的所有文章。如果我点击来自 first_app 的文章(比如发布在 first_app 上的第三篇文章),我将被定向到 url 127.0.0.1:8000/first_app/3
。同样,如果我点击 third_app 中的一篇文章(比如发布在 third_app 上的第二篇文章),我将被定向到 url 127.0.0.1:8000/third_app/2
。
我不确定如何遍历我应用程序的所有模型来获取 Article 表的数据。而且我不确定如何生成 URL 来反射(reflect)文章来自的应用程序。我尝试了一些东西,但没有任何效果。我被困在这一点上。 我是 Django 的新手,所以请给我一些有用的评论或解决方案,而不是回答我的问题。
我应该如何更改我的 View 、url 和 html 页面来执行此操作?谢谢。
最佳答案
对于 URL 问题,在模型上使用 get_absolute_url 功能,
关于在应用程序中迭代所有模型的问题,你不需要在模板中做任何事情,你应该在 View 中收集你需要的数据并将其呈现给模板进行渲染,所以答案是您在 View 中选择所需的模型,然后将其发送到模板。
但是应用应该是可重用的组件,如果您的应用之间存在严重的依赖关系,则很难激励它们成为独立的应用。
关于python - 从单个 html 页面上的多个 django 应用程序模型获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16135659/