我真的不知道还能做什么但是来到这里问你们。继承人的情况:
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!!!!!!!!!!!!!!!
我试图看到表单中的错误,似乎没有人。我在表单的干净方法上放了一些标记,但它们没有被调用。 Sames用于OptionChoiceField中的clean方法。
视图中的以下代码
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
答案 0 :(得分:5)
您将覆盖默认构造函数,因此它接受一个查询集,因此您应该这样做:
qs = OptionVote.objects.all()
form = OptionVoteForm(qs, request.POST)