'QueryDict'对象没有属性'id'

时间:2012-12-29 19:12:14

标签: python django django-forms

在'面板'页面上,我有一个选择字段,其中包含已上传文档的列表或'bots',因为我通常会引用它们。此列表仅显示当前用户上传的“机器人”。

panel\forms.py

from django import forms
import os

from upload.models import Document

#### RETRIEVE LIST OF BOTS UPLOADED BY CURRENT USER ####
def get_files(user):
    bots = Document.objects.filter(user=user.id)
    file_list = []
    for b in bots:
        file_list.append((b.id,b.docfile))
    return file_list

class botForm(forms.Form):

    def __init__(self, user, *args, **kwargs):
        super(botForm, self).__init__(*args, **kwargs)
        self.fields['bot'] = forms.ChoiceField(choices=get_files(user))

这很好用,并显示所有用户机器人的列表。当我尝试将这些值传递到“游戏”页面并在此处访问它们时,会出现问题。

game\views.py

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from game.models import game
from game.forms import GameForm
from upload.models import Document
from panel.forms import botForm
import league

def RPS(request):
    if request.method == 'POST': # If the request is a POST method...

        if 'PanelPlay' in request.POST:
            panel = botForm(request.POST)
            if panel.is_valid():
                print panel.cleaned_data['bot']

        elif 'GamePlay' in request.POST:
            form = GameForm(request.POST) # A form bound to the POST data
            if form.is_valid(): # All validation rules pass
                leagueOuput = []
                leagueOutput = league.run(form.cleaned_data['bot1'],form.cleaned_data['bot2'])
                newGame = game()
                newGame.bot1 = leagueOutput[0]
                newGame.bot2 = leagueOutput[1]
                newGame.bot1wins = leagueOutput[2]
                newGame.bot2wins = leagueOutput[3]
                newGame.save()
                return HttpResponseRedirect(reverse('game.views.RPS')) # Redirect after POST

    form = GameForm() # An unbound form
    results = game.objects.all()    # Load messages for the list page     

    return render_to_response('game.html', {'results': results, 'form': form}, context_instance=RequestContext(request))

尝试访问和验证面板数据时,出现以下错误。

  

'QueryDict'对象没有属性'id'

参考这一具体路线。

bots = Document.objects.filter(user=user.id)

我已经找到并阅读了许多类似的问题,但我似乎无法将他们的解决方案延伸到我自己的项目中。

提前感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:8)

在构建botForm时,您将request.POST(一个QueryDict)作为user参数传递。你的意思是

panel = botForm(request.user, data=request.POST) 

(假设你正在使用django身份验证)。