简体   繁体   中英

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. 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

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

from django.conf.urls import patterns, url

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

This is my 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

{% 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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