【问题标题】:Django: objects are not showing at index pageDjango:对象未显示在索引页面上
【发布时间】:2021-01-20 14:33:38
【问题描述】:

这是我的第一个 Django 项目,但遇到了问题。我在后端创建了新闻,但在首页显示新闻时遇到问题。模型应该没问题,因为我可以在管理面板中创建新闻。但我不知道我的错误在哪里。

我有应用“页面”>views.py

from django.shortcuts import render, redirect, get_object_or_404
from mainnews.models import Mainnews

# Create your views here.
def home_view(request):
    main = Mainnews.objects.all()

    context = {
        'main' : main
    }
    return render(request, 'index.html', context)

root>urls.py

from pages.views import home_view
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home_view, name = 'home'),
]

和 app mainnews>views.py

from django.shortcuts import render, get_object_or_404
from .models import Mainnews
# Create your views here.

def index(request):
    main = Mainnews.objects.all()
    context = {
        'main' : main
    }
    return render(request, 'index.html', context)

以及扩展至索引的模板 mainnewsandevents.html

{% block content %}
  <!-- Section 2 News and Events -->
  <div id="news-container">
    <div class="jumbo-news">
        <img id = 'jumboImgUrl' class='jumbo-img' src="{{ main.image.url }}">
        <h2 id = 'jumboTitle' class='jumbo-title'>{{ main.title }}</h2>
        <h4 id = 'jumboDescription' class='jumbo-parag'>{{ main.description }}</h4>
    </div>
{% endblock %}

【问题讨论】:

    标签: django


    【解决方案1】:

    像这样修复它:

    def home_view(request):
        main = Mainnews.objects.first()
        # or main = Mainnews.objects.last()
        # other code
    

    或者如果您需要在模板上显示所有对象,请使用类似的东西:

    {% block content %}
      <!-- Section 2 News and Events -->
      <div id="news-container">
        <div class="jumbo-news">
            {% for article in main %}
                <img id = 'jumboImgUrl' class='jumbo-img' src="{{ main.image.url }}">
                <h2 id = 'jumboTitle' class='jumbo-title'>{{ main.title }}</h2>
                <h4 id = 'jumboDescription' class='jumbo-parag'>{{ main.description }}</h4>
            {% endfor %}
        </div>
    {% endblock %}
    

    取决于您的需求。
    此外,您不应该为变量使用不明显的名称,因此您应该使用 main_news 而不是 main。

    【讨论】:

      【解决方案2】:

      ma​​in 是一个对象数组,因此您需要一个 for 循环来获取每个对象

      {% block content %}
        <!-- Section 2 News and Events -->
        <div id="news-container">
          <div class="jumbo-news">
              {% for obj in main %}
                  <img id = 'jumboImgUrl' class='jumbo-img' src={{ obj.image.url }}>
                  <h2 id = 'jumboTitle' class='jumbo-title'>{{ obj.title }}</h2>
                  <h4 id = 'jumboDescription' class='jumbo-parag'>{{ obj.description }}</h4>
              {% endfor %}
          </div>
      {% endblock %}
      

      【讨论】:

        猜你喜欢
        • 2017-07-23
        • 1970-01-01
        • 2011-11-22
        • 2015-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-31
        • 1970-01-01
        相关资源
        最近更新 更多