在Django中验证表单时遇到问题
我真的不知道该怎么办,只好来这里问你们。情况是这样的:
models.py
class Vote(models.Model):
""" Generic vote model """
user = models.ForeignKey(User)
question = models.ForeignKey(Question)
created = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
cache = CacheVoteManager()
class Meta:
abstract = True
def __unicode__(self):
return '%s : %s' % (self.user.username, self.question.question)
class OptionVote(Vote):
option = models.ForeignKey(Option)
forms.py
class OptionChoiceField(forms.ModelChoiceField):
""" Custom model choice field for options """
widget = forms.RadioSelect(attrs={'class': 'c-opt'})
def label_from_instance(self, obj):
return mark_safe(
'<span class="c-opt-img">%s</span><span class="c-opt-name">%s</span>'
% (obj.media_content.draw_create_widget() , obj.name))
class OptionVoteForm(ModelForm):
""" Form to vote in a option-based question """
option = OptionChoiceField(queryset=OptionVote.objects.none(),
empty_label=None)
class Meta:
model = OptionVote
exclude = ['user', 'question']
def __init__(self, options=None, *args, **kwargs):
super(OptionVoteForm, self).__init__(*args, **kwargs)
if options:
self.fields['option'].queryset = options
views.py
form = OptionVoteForm(request.POST)
form.is_valid()
>> FALSE!!!!!!!!!!!!!!!
我试着查看表单中的错误,但似乎没有发现任何问题。我在表单的清理方法上加了一些标记,但它们没有被调用。OptionChoiceField中的清理方法也是一样。
在视图中的以下代码
print 'PRINTING ERRORS: ' + str(form.errors)
for field in form:
print str(field.label_tag()) + ': ' + str(field.errors)
返回:
PRINTING ERRORS:
<label for="id_option_0">Option</label>:
请帮帮我,我真的在这个问题上卡住了。
编辑 当我尝试这样做
form = OptionVoteForm(request.POST)
print form
我收到以下错误:
Exception Type: AttributeError
Exception Value: 'QueryDict' object has no attribute 'all'
ExceptionLocation: /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/forms/models.py in __iter__, line 882
哦,顺便说一下,我正在使用django 1.3
1 个回答
5
你正在重写默认的构造函数,使它能够接受一个查询集(queryset),所以你应该这样做:
qs = OptionVote.objects.all()
form = OptionVoteForm(qs, request.POST)