我有一个名为Project_Name的项目和一个名为first_app的应用程序,其中包含一些文章。 我在我的主页上显示这些文章标题作为应用页面上文章的链接。从单个html页面上的多个django应用模型获取数据
所以在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)),
...
这里是我的models.py我first_app应用程序中:
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})
这是我detail.html在我的first_app模板文件夹:
{{ article.name }}
Published On: {{article.pub_date }}
Content:
- {{ article.content }}
这里是我的项目主页,index.html的:
{% if latest_article_list %}
Latest Articles
{% for article in latest_article_list %}
{{article.name }}{% endfor %}
{% else %}
No articles are available.
{% endif %}
这是所有工作的罚款。
我的问题: 如果我有两个或更多的应用程序,每一个都有自己的文章(我打破了由其他原因不同的应用程序的文章),我怎么会得到在主页上的文章?以及我如何构建这些网址,当我点击主页上的一篇文章时,它会将我带到正确的应用网址?
因此,例如,我有应用程序: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。
我不知道如何迭代我的应用程序的所有模型来获取文章表格的数据。我不知道如何生成网址来反映文章的来源。我尝试了一些东西,但没有任何工作。我坚持在这一点上。 我对Django很新,所以请给我一些有用的意见或解决方案,而不是敲掉我的问题。
我该如何改变我的意见,网址和html页面来做到这一点?谢谢。
2013-04-21
brno792