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

2024-06-16 14:11:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我不能让我的主页显示我的主页和IconBlurb模型的数据。我在这个问题上耽搁了两天,想不通。请帮帮我。谢谢

这是我的模特

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")

这是我的观点

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)

这是我的url.py

from django.conf.urls import patterns, url

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

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

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

Tags: divindexmodelsrequesthtmllatestlengthmax
1条回答
网友
1楼 · 发布于 2024-06-16 14:11:11

这很简单。在一个函数中编写两个函数代码

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)

相关问题 更多 >