【问题标题】:NameError in DjangoDjango中的名称错误
【发布时间】:2013-03-06 22:30:18
【问题描述】:

我正在使用 Django/python 并遇到了一些错误,我似乎无法在网上找到相关答案。

我正在从 views.py 中测试以下内容:

def teamRoster(request, pk): #shows list of players

    tempteams = Teams.objects.get(id=pk)
    tempteams = tempteams.players.all()
    team = get_object_or_404(Teams, id=pk)

    context = {
        'teamList': tempteams,
        'team': team,
    }

return render(request, "roster/teamRoster.html", context)

我在 shell 中得到了什么:

from roster.models import Teams, Player
tempteams=Teams.objects.get(id=pk)

Traceback (most recent call last):
File "<console>", line 1, in <module>

NameError: name 'pk' is not defined

如果我尝试下一行:

tempteams = tempteams.players.all()

Traceback (most recent call last):
File "<console>", line 1, in <module> 

NameError: name 'tempteams' is not defined

我的数据确实有一个 pk 属性,我在制作我的 json 文件时输入了该属性,而不是自动分配一个。我不确定我需要在哪里定义 pk。我对 django/python 相当陌生,但我确实对另一个定义(同一个项目)做了类似的事情,而且效果很好。任何指导将不胜感激。如果有帮助,我的模型和代码的其他部分位于 https://github.com/historymaiden/Athletic-Team-App - 该应用程序称为 roster。

【问题讨论】:

    标签: python-2.7 django-views


    【解决方案1】:

    你还没有在 shell 中定义 pk 这就是你在那里得到错误的原因

    from roster.models import Teams, Player
    tempteams=Teams.objects.get(id=pk)
    
    Traceback (most recent call last):
    File "<console>", line 1, in <module>
    
    NameError: name 'pk' is not defined
    

    因为最后一个代码块失败了,所以也没有定义 tempteams

    tempteams = tempteams.players.all()
    
    Traceback (most recent call last):
    File "<console>", line 1, in <module> 
    
    NameError: name 'tempteams' is not defined
    

    【讨论】:

      猜你喜欢
      • 2016-10-14
      • 1970-01-01
      • 2016-05-25
      • 2017-12-13
      • 2014-08-17
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多