1

選択して送信をクリックすると、このエラーが表示されます。ページのフォームで HiddenInput を使用して非表示にしようとしています。forms.py 以外でそれを行う別の方法はありますか

モデル.py

from django.db import models from django.utils import timezone
from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from random import randrange

class Type(models.Model):
    type = models.CharField(max_length=50)

    def _unicode__(self):
        return self.type

class WordManager(models.Manager):

    def random(self, type):
       words = Word.objects.filter(type__type=type)

       return words[randrange(len(words))]


class Word(models.Model):
    dict = models.CharField(max_length=200)
    type = models.ForeignKey(Type)

    objects = WordManager()

    def __unicode__(self):
       return u'%s %s' % (self.dict, self.type)

class Question(models.Model):
    question = models.CharField(max_length=200)

    def __unicode__(self):
        return self.question


class Meta(models.Model):
    user = models.CharField(max_length=200)
    time = models.DateTimeField('date published')

class Result(models.Model):
    question = models.ForeignKey(Question)
    word = models.ManyToManyField(Word)
    user = models.ForeignKey(User)
    score = models.IntegerField()

Forms.py

from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm

from quest.models import Result, Question, Word

class ResultForm(ModelForm):
    CHOICES = (
('1', '1'), ('2','2'), ('3','3'), ('4', '4'), ('5', '5')
)
question = forms.ModelChoiceField(queryset=Question.objects.all(), widget=forms.HiddenInput())
word = forms.ModelChoiceField(queryset=Word.objects.all(), widget=forms.HiddenInput())
user = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.HiddenInput())
score = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())

class Meta:
    model = Result


class UserForm(ModelForm):
    class Meta:
       model = User
       fields = ('username',)

Views.py

from django.contrib.auth import authenticate, login
from django.core.urlresolvers import reverse
from django.shortcuts import render, render_to_response, HttpResponseRedirect
from django.template import RequestContext
from django.utils import timezone

from random import randrange
import re

from quest.models import Word, Type, Question, Meta
from quest.forms import ResultForm, UserForm

def index(request):
    state = "Enter ID and password below"
    username = password = ''
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                state = "You're successfully logged in!"
            else:
                state = "Your account is disabled."
        else:
            state = "Your username and password were incorrect."

     return render_to_response('index.html',{'state':state, 'username': username}, context_instance=RequestContext(request))


def question(request):
    # Find all words to be replaced from the question marked by '$'
    question = Question.objects.get(id=1)

    word_types = re.findall(r"\w+[$]", question.question)
    word_types = [find_w.rstrip("$") for find_w in word_types]
    words = [Word.objects.random(type) for type in word_types]

    question_text = question.question.replace("$", "")
    for word in words:
        question_text = question_text.replace(word.type.type, word.dict)
for word in words:
    question_text = question_text.replace(word.type.type, word.dict)

if request.method == 'POST':
    form = ResultForm(request.POST)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse('question'))
    else:
        for error in form.errors:
            print error
else:
    form = ResultForm(initial={'question': question.id, 'word': [word.id for word in words], 'user': request.user.id})

return render_to_response('quest/question.html', {'final': question_text, 'form': form}, context_instance=RequestContext(request))
4

1 に答える 1

0
word = forms.ModelChoiceField(queryset=Word.objects.all(), widget=forms.HiddenInput())

誰も選択できない場合、選択フィールドであることのポイントは何ですか? わかりました、今私はあなたがやろうとしていることを手に入れました。しかし、以下はまだ適用されます。

これも:

'word': [word.id for word in words]

initialフォームデータが間違っています。ModelChoiceFieldpresentsには多くの選択肢がありますが、選択できるのは1 つだけです。それで'word': someword.id正しいでしょう。

補足として、これはモデルからランダムなデータを選択する方法に役立つかもしれませ

于 2012-10-09T20:45:58.893 に答える