简体   繁体   English

如何使两个模型同时出现在Django主页上?

[英]How can I make two models appear on my Django homepage simultaneously?

I can't make my homepage show data from both my HomePage and IconBlurb models. 我无法使主页显示来自HomePage和IconBlurb模型的数据。 I've been stucked on this problem for two days and couldn't figure it our. 我已经在这个问题上停留了两天,无法解决这个问题。 Please help me. 请帮我。 Thanks. 谢谢。

This is my models.py 这是我的模型

class HomePage(models.Model):
    heading = models.CharField(max_length=200,
     help_text="The heading under the icon blurbs")
    subheading = models.CharField(max_length=200,
     help_text="The subheading just below the heading")
    introduction = models.TextField(help_text="首页的欢迎文字。")
    introLink = models.URLField(max_length=200, blank=True)

    class Meta:
      verbose_name= _("Home page")
      verbose_name_plural = _("Home pages")

This is my views.py 这是我的views.py

from django.shortcuts import get_object_or_404, render
from homepage.models import HomePage, IconBlurb

def index(request):
    homepage = get_object_or_404(HomePage)
    return render(request, 'homepage/index.html', {'homepage':homepage})

def blurb(request):
    latest_iconblurb = IconBlurb.objects.all()
    context = {'latest_iconblurb': latest_iconblurb}
    return render(request, 'homepage/blurb.html', context)

This is my urls.py 这是我的urls.py

from django.conf.urls import patterns, url

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    )

This is my index.html 这是我的index.html

{% extends "base.html" %}
{% block all_content %}
<div class="jumbotron">
    <div class="container">
        <h1>{{ homepage.heading }}</h1>
        <p>{{ homepage.introduction }}</p>
        <p><a class="btn btn-primary" href="/courses">开始学习</a></p>
    </div>
</div>
<div class="container">
    <div class="row">
        {% block blurb %}{% endblock %}
    </div>
</div>
{% endblock %}

This is my blurb.html 这是我的blurb.html

{% extends "homepage/index.html" %}

{% block blurb %}
{% if latest_iconblurb %}
{% for blurb in latest_iconblurb %}
<div class="col-md-4">
    <h2>{{ blurb.title }}</h2>
    <p>{{ blurb.content }}</p>
</div>
{% endfor %}
{% endif %}
{% endblock %}

This is simple. 这很简单。 Write both function code in a single function. 在一个函数中编写两个函数代码。

def index(request):
    homepage = get_object_or_404(HomePage)
    latest_iconblurb = IconBlurb.objects.all()
    context = {'latest_iconblurb': latest_iconblurb; 'homepage':homepage}
    return render(request, 'homepage/blurb.html', context)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM