简体   繁体   English

它不会将 QuerySet 过滤器数据返回到 HTML

[英]it is not return QuerySet filter data to HTML

I am trying the following code to print all data into the HTML page.我正在尝试使用以下代码将所有数据打印到HTML页面中。 when I am printing the data in command prompt it works properly but not printing data into the HTML .当我在命令提示符下打印数据时,它可以正常工作,但不能将数据打印到HTML中。

view.py output of view.py in command prompt I want to print same data to HTML命令提示符中view.py的 view.py output 我想将相同的数据打印到HTML

def previousYear(request):
    Subjects = Subject.objects.all()
    filters = None
    Papers = None
    print("=========================================================")
    if request.method == "POST":
        if (request.POST.get("Year") != "") & (request.POST.get("Department") != ""):
            a = request.POST.get("Year")
            b = request.POST.get("Department")
            filters = Subjects.filter(Year=a,Department_id=b)
            for i in filters:
                Papers = Pre_Q_Paper.objects.filter(Subjects=i)
                if Papers.exists():
                    print(i)
                    for j in Papers:
                        print(j)
    data = {"papers":Papers,
            "filters":filters}
    return render(request,"Previous.html", data)

main.html main.html

{%for i in filters%}
   <h2>{{i}}</h2>
   {% for item in papers %}
       <h2>{{ item }}</h2>
       {% endfor %}
{% endfor %}

I'm a little confused by what you're trying to do in your view.我对您在您看来要做什么感到有些困惑。 First of all I don't understand why you would POST to the view, as you are trying to get data.首先,当您尝试获取数据时,我不明白您为什么要发布到视图中。

I would suggest something like this for your views.py我会为你的views.py建议这样的东西

def previous_year(request):
    data = {
      "papers": [],
      "subjects": [],
    }
    if request.method == 'GET':
      year = request.GET.get('year', '')
      dep_id = request.GET.get('department', '')
      if year and dep_id:
        subjects_filtered = Subjects.objects.filter(Year=year, Department_id=dep_id)
        papers = Pre_Q_Paper.objects.filter(Subjects__in=subjects_filtered)
        data["papers"] = papers
        data["subjects"] = subjects_filtered


    return render(request, "Previous.html", data)

and then in your Previous.html然后在你的Previous.html

{% for subject in subjects %}
   <h2>{{ str(subject) }}</h2>
   {% for paper in papers %}
       {{ str(paper) }}<br />
   {% endfor %}
{% endfor %}

Then you submit the year and department id through query parameters like so:然后通过查询参数提交年份和部门 ID,如下所示:

<view_url>?year=2018&department=2 <view_url>?year=2018&department=2

Please follow this tutorial if you're having difficulties getting started如果您在入门时遇到困难,请遵循本教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM