Hello!
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 = 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?