【问题标题】:How to solve when Django views.py is not passing the dictionary value to html?当 Django views.py 没有将字典值传递给 html 时如何解决?
【发布时间】:2020-07-30 22:02:18
【问题描述】:

我在 views.py 中有一个字典值并将其呈现到前端。当我在 html 中遍历字典时,只显示一个值,而其他值不显示。这可能是什么问题?

views.py

def Student_Create(request):
    form = Student_Model_Form(request.POST or None)
    # get class names and days
    classes = Create_Class.objects.all()
    cls = {}
    for i in classes:
        cls[i] = {
            'class_name': i.class_name,
            'from_day': str(i.from_days),
            'to_day': str(i.to_days),
            'from_time': i.from_time.strftime("%H:%M:%S"),
            'to_time': i.to_time.strftime("%H:%M:%S"),
        }
    print(cls)
    template_name = 'genius/students_create.html'
    context = {'form': form, 'classes': cls}
    return render(request, template_name, context)

student.html

<div class="form-group">
  <label for="select-class">Select Class</label>
  <select class="custom-select" multiple name="select-class">
     {% for i in classes%}
      <option value="{{i.class_name}}">{{i.class_name}} : {{i.from_day}}-{{i.to_day}}</option>
     {% endfor %}
  </select>
</div>

而最终的输出是这样的。

See The Output

您的帮助将不胜感激。

【问题讨论】:

    标签: html django python-3.x django-views django-templates


    【解决方案1】:

    您可以使用列表来存储数据:

    ...
    cls = []  # Change from dict to list.
    for i in classes:
        cls.append({
            'class_name': i.class_name,
            'from_day': str(i.from_days),
            'to_day': str(i.to_days),
            'from_time': i.from_time.strftime("%H:%M:%S"),
            'to_time': i.to_time.strftime("%H:%M:%S"),
        })
    ...
    

    【讨论】:

    • 哦,是的,我忘记了列表。谢谢
    【解决方案2】:

    而不是像上面那样创建字典。你可以做 视图.py

    def Student_Create(request):
        form = Student_Model_Form(request.POST or None)
        # get class names and days
        classes = Create_Class.objects.values_list('class_name', 'from_days', 'to_days' ,'from_time', 'to_time', flat=True)
        template_name = 'genius/students_create.html'
        context = {'form': form, 'classes': classes}
        return render(request, template_name, context)
    
    
    

    【讨论】:

    • 这可能是更好的解决方案,代码更少。谢谢!
    • @VikrantAgrahari,您可以投票或接受该解决方案。
    • 我接受这个解决方案。我猜我不能为声誉低下的原因投票。
    猜你喜欢
    • 1970-01-01
    • 2016-03-12
    • 2019-09-21
    • 1970-01-01
    • 2015-04-19
    • 2018-12-23
    • 1970-01-01
    • 2012-04-07
    • 1970-01-01
    相关资源
    最近更新 更多