【问题标题】:django - I don't see anything from database when i want to display the contents on cards/index pagedjango - 当我想在卡片/索引页面上显示内容时,我没有从数据库中看到任何内容
【发布时间】:2019-02-16 00:02:08
【问题描述】:

django - 当我想在卡片/索引页面上显示内容时,我没有从数据库中看到任何内容。在管理部分它正在工作,但在这里不起作用。顺便说一句,对不起我的沟通不畅

urls.py

from django.urls import path
from . import views

urlpatterns = [
  path('', views.all_id_cards),
 ]

views.py

 from django.shortcuts import render
 from .models import IdCard

def all_id_cards(request):
    cards = IdCard.objects.all()
    return render(request, 'cards/cards_index.html', { 'cards': cards })

models.py

from django.db import models

# Create your models here.
class IdCard(models.Model):
   emp_id = models.CharField(max_length=12)
   emp_name = models.CharField(max_length=40)
   emp_title = models.CharField(max_length=30)
   emp_telephone = models.CharField(max_length=12)
   emp_email = models.CharField(max_length=30)
   emp_generation = models.CharField(max_length=20)
   emp_status = models.CharField(max_length=20)

   def __str__(self):
      return self.emp_name

cards_index.html

    <!DOCTYPE html>
  <html>
    <head>
        <meta charset="utf-8">
        <title>Homepage</title>
    </head>
    <body>
        <h1>Identity Cards</h1>
        <div class="identitycards">
            {% for cards in cards %}
                <div class="identitycard">
                    <p>{{ IdCard.emp_name }}</p>
                </div>
            {% endfor %}
        </div>
    </body>
</html>

【问题讨论】:

    标签: python html css django database


    【解决方案1】:

    这里有两个问题:

    1. 您使用{% for cards in cards %} 迭代项目,因此迭代器 与集合具有相同的名称。尽管它可能起作用,但最好避免这样做,因为它可能导致不可预测的行为;和
    2. 您使用{{ IdCard.emp_name }} 呈现内容。 IdCard 没有传递给渲染,但无论如何,你需要使用card,所以{{ card.emp_name }}

    如果我们修复了我们作为模板文件得到的两个问题:

    <!DOCTYPE html>
      <html>
        <head>
            <meta charset="utf-8">
            <title>Homepage</title>
        </head>
        <body>
            <h1>Identity Cards</h1>
            <div class="identitycards">
                {% for card in cards %}
                    <div class="identitycard">
                        <p>{{ card.emp_name }}</p>
                    </div>
                {% endfor %}
            </div>
        </body>
    </html>

    【讨论】:

    • 是的,我写的答案基本相同。我要删除我的,你的速度更快!
    • 感谢您的帮助。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多