将名称绑定到Django中的类的问题

时间:2010-04-20 13:26:58

标签: python django class django-views

我有一个视图函数,必须根据某些条件决定使用哪种表单。这两种形式看起来像这样:

class OpenExtraForm(forms.ModelForm):
    class Meta:
        model = Extra

    def __init__(self, *args, **kwargs):
        super(OpenExtraForm, self).__init__(*args, **kwargs)

        self.fields['opening_challenge'].label = "lame translation"

    def clean_opening_challenge(self):
        challenge = self.cleaned_data['opening_challenge']
        if challenge is None:
            raise forms.ValidationError('Укажите шаг, открывающий данную доп. возможность')
        return challenge

class HiddenExtraForm(forms.ModelForm):
    class Meta:
        model = Extra
        exclude = ('opening_challenge')

    def __init__(self, *args, **kwargs):
        super(HiddenExtraForm, self).__init__(*args, **kwargs)

视图代码如下:

@login_required
def manage_extra(request, extra_id=None, hidden=False):
    if not_admin(request.user):
        raise Http404
    if extra_id is None:
        # Adding a new extra
        extra = Extra()
        if hidden:
            FormClass = HiddenExtraForm
        else:
            FormClass = OpenExtraForm
    else:
        # Editing an extra
        extra = get_object_or_404(Extra, pk=extra_id)
        if extra.is_hidden():
            FromClass = HiddenExtraForm
        else:
            FormClass = OpenExtraForm

    if request.POST:
        form = FormClass(request.POST, instance=extra)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse(view_extra, args=[extra.id]))
    else:
        form = FormClass(instance=extra)
    return render_to_response('form.html', { 'form' : form,
                                              }, context_instance=RequestContext(request) )

问题如果extra.is_hidden()返回True,则语句FromClass = HiddenExtraForm不起作用。我的意思是,在代码中使用的所有其他条件下它工作正常:正确的Form类被实例化并且它都可以工作。但是如果extra.is_hidden(),调试器会显示条件已通过并且它会转到下一行并且什么都不做!结果我得到一个UnboundLocalVar错误,表示FormClass根本没有被分配。

有关正在发生的事情的任何想法?

1 个答案:

答案 0 :(得分:4)

您需要在FromClassFormClass之间做出决定。您可以在任何地方使用FormClass,除了:

    if extra.is_hidden():
        FromClass = HiddenExtraForm