如何在Django主页上同时显示两个模型?

时间:2023-01-12 19:33:39

I can't make my homepage show data from both my HomePage and IconBlurb models. I've been stucked on this problem for two days and couldn't figure it our. Please help me. Thanks.

我无法从我的HomePage和IconBlurb模型中显示我的主页显示数据。我已经被困在这个问题上两天了,无法理解我们的问题。请帮帮我。谢谢。

This is my models.py

这是我的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 %}

1 个解决方案

#1


1  

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)

#1


1  

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)