开发者

Problem bounding name to a class in Django

I've got a view function that has to decide which form to use depending on some conditions. The two forms look like that:

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)

The view code goes like that:

@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 开发者_JS百科= 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) )

The problem is somehow if extra.is_hidden() returns True, the statement FromClass = HiddenExtraForm doesn't work. I mean, in all other conditions that are used in the code it works fine: the correct Form classes are intantiated and it all works. But if extra.is_hidden(), the debugger shows that the condition is passed and it goes to the next line and does nothing! As a result I get a UnboundLocalVar error which says FormClass hasn't been asssigned at all.

Any ideas on what's happening?


You need to decide between FromClass and FormClass. You use FormClass everywhere except:

    if extra.is_hidden():
        FromClass = HiddenExtraForm
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜