简体   繁体   English

Django,我无法将变量从视图传递到 html 模板

[英]Django, I'm not able to pass a variable from Views to html template

Good day, I'm new to Django and following CS50Web.美好的一天,我是 Django 和 CS50Web 的新手。 I've been having a headache for a couple of days trying to understand why this is not working.几天来我一直头疼,试图理解为什么这不起作用。 Basically we have a Flights model and a Passengers model with a many-to-many relationship.基本上,我们有一个航班 model 和一个乘客 model 具有多对多关系。 here is the views.py code:这是views.py代码:

def flight(request, flight_id):
    flight = Flight.objects.get(pk=flight_id)
    passengers = flight.passengers.all()
    print(passengers)
    return render(request, "flights/flight.html", {
        "flight": flight,   
        "passengers:": passengers
    })

and here is the html:这是 html:

<h2> Passengers </h2>
    <ul>
        {% for passenger in passengers %}
            <li>{{ passenger }}</li>
        {% empty %}
            <li>No passengers.</li>
        {% endfor %}
    </ul>

I know the passengers variable is not empty, the print statement returns: "<QuerySet [<Passenger: Fidel Castro>, <Passenger: James Bond>, <Passenger: Larry Bird>]>"我知道乘客变量不为空,打印语句返回:“<QuerySet [<Passenger: Fidel Castro>, <Passenger: James Bond>, <Passenger: Larry Bird>]>”

Still, the rendered Html page always shows no passengers!尽管如此,渲染的 Html 页面始终没有显示任何乘客!

Could a good soul help me understand what I'm I doing wrong?一个好的灵魂能帮助我理解我做错了什么吗? Because I'm out of ideas at this point.因为我现在没有想法。 Thank you in advance先感谢您

Try to not use the same variables name as in your models fields or model name.尽量不要使用与模型字段中相同的变量名称或 model 名称。

Remove the colon ":" at the end of "passengers:" in the context dictionary.删除上下文字典中“passengers:”末尾的冒号“:”。

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

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