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

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)


我发现并阅读了许多类似的问题,但似乎无法将他们的解决方案用于我自己的项目。

在此先感谢您提供的所有帮助。

最佳答案

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

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




(假设您正在使用Django身份验证)。

10-04 12:30