【问题标题】:What is wrong with this Django code for template and model这个模板和模型的 Django 代码有什么问题
【发布时间】:2020-03-06 09:10:32
【问题描述】:

所以我正在尝试使用 Django 制作动态页面。 我已经在管理页面中输入了“名称”、“背景”和“介绍”数据。现在我正试图将其展示给我的“.../index”页面。但它不起作用。

这是models.py的python代码

class UserInfo(models.Model):
    name = models.CharField(max_length = 10)
    background = models.CharField(max_length=30)
    introduction = models.CharField(max_length = 60)

在我的 views.py 文件中,我有这个:

def index(request):
    user = UserInfo.objects.all()
    return render(request, 'index.html', {'user' : user})

最后在我的 'index.html' 文件中,我有这个:

<p>{{user.name}}</p>
<p>{{user.background}}</p>
<p>{{user.introduction}}</p>

所以这些代码应该在“.../index”页面中向我显示名称、背景和介绍,但它什么也没显示。 我看不出我做错了什么。

非常感谢您的帮助。 :) 谢谢。

【问题讨论】:

    标签: python django


    【解决方案1】:

    您的user 变量是用户列表,因此您需要在模板中对其进行迭代

    {% for item in user %}
        <p>{{item.name}}</p>
        <p>{{item.background}}</p>
        <p>{{item.introduction}}</p>
    {% endfor %}
    

    或在index()中获取特定用户

    def index(request):
        user = UserInfo.objects.get(pk = your_user_pk)
        return render(request, 'index.html', {'user' : user})
    

    那么你的模板应该可以工作

    <p>{{user.name}}</p>
    <p>{{user.background}}</p>
    <p>{{user.introduction}}</p>
    

    【讨论】:

    • 天哪,它帮了很多忙。非常感谢!
    【解决方案2】:

    UserInfo.objects.all() 返回列表,所以你已经使用 first() 获取第一个元素

    def index(request):
        user = UserInfo.objects.all().first()
        return render(request, 'index.html', {'user' : user})
    

    【讨论】:

      【解决方案3】:

      UserInfo.objects.all() 将返回一个 QuerySet 对象而不是单个实例。

      如果您只想根据最新的 id 呈现一个用户,您可以执行以下操作:

      def index(request):
          user = UserInfo.objects.latest('id')
          return render(request, 'index.html', {'user' : user})
      

      如果您想按照@weAreStarDust 的建议在您的页面上呈现所有用户,您可以这样做(在您的views.py 中将user 重命名为users 以避免混淆)

      {% for user in users %}
          #Do Something with user
          <p>{{user.name}}</p>
          <p>{{user.background}}</p>
          <p>{{user.introduction}}</p>
      {% endfor %}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-18
        • 1970-01-01
        相关资源
        最近更新 更多