【问题标题】:How to display model field on html page - Django如何在 html 页面上显示模型字段 - Django
【发布时间】:2015-04-23 08:47:17
【问题描述】:

我正在尝试在用户个人资料页面上显示当前课程数量,但无法显示。

这是我的models.py:

class LessonCount(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    lesson_current_amount = models.PositiveIntegerField(default=0, verbose_name='Current Number of Lessons')

    def __unicode__(self):
        return str(self.user.username)

views.py:

@login_required
def user_profile(request):
    user = None
    lessoncount = LessonCount.objects.all()
    context = {
        'user': user,
        'lessoncount': lessoncount
    }
    return render(request, 'account/profile.html', context)

profile.html:

{% extends 'base.html' %}

{% block content %}

<h3 style="color: red;">{{ lessoncount.lesson_current_amount }}</h3>

<h3 style="color: red;">{{ request.user.username }}</h3>

{% endblock %}

提前致谢!

【问题讨论】:

    标签: python html django django-models django-views


    【解决方案1】:

    您需要一个LessonCount 对象,但LessonCount.objects.all() 是一个QuerySet

    将该行更改为:

    lessoncount = LessonCount.objects.get(user=request.user)
    

    【讨论】:

      【解决方案2】:

      你需要遍历对象:

      {% for lesson in lessoncount %}
      
      <h3 style="color: red;">{{ lesson.lesson_current_amount }}</h3>
      
      {% endfor %}
      

      阅读更多关于for循环in the docs的信息。

      【讨论】:

        猜你喜欢
        • 2013-04-20
        • 2019-01-08
        • 2020-09-30
        • 2019-09-03
        • 1970-01-01
        • 2018-11-13
        • 2019-10-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多