views:

44

answers:

1

I was trying to pass an additional parameter to my form, which is anObject to ForeignKey relation. But dunno why form returns __init__() got an unexpected keyword argument 'parent' when I'm pretty sure that it is possible to send additional parameters to form's __init__ (ie here : http://stackoverflow.com/questions/3182262/simple-form-not-validating/3189499#3189499). Am I wrong ?

def add_video(request):
    parent = ParentObject.objects.all()[0]
    if request.method == 'POST':
        form = VideoForm(data=request.POST, parent=parent)
        if form.is_valid():
            form.save()            
            next = reverse('manage_playforward',)
            return HttpResponseRedirect(next)
    else:
        form = VideoForm()

class VideoForm(forms.ModelForm):       

    def __init__(self, *args, **kwargs):
        try:
            self.parent = kwargs.pop['parent']
            logging.debug(self.parent)
        except:
            pass    
        super(VideoForm, self).__init__(*args, **kwargs)
+6  A: 

kwargs.pop['parent'] is throwing TypeError: 'builtin_function_or_method' object is unsubscriptable, because you're trying to do a key lookup on a function method ({}.pop). This error is then being swallowed by your exception handler.

For this to work do kwargs.pop('parent', None). In your case:

class VideoForm(forms.ModelForm):       
    def __init__(self, *args, **kwargs):
        self.parent = kwargs.pop('parent', None)
        super(VideoForm, self).__init__(*args, **kwargs)

As a side note, 99% of time its best to only catch specific Exceptions in your except blocks. Doing so will help dodge bugs/confusion like this. Also, I would highly suggest adding unit tests for this custom construction (or just TDDing your other code, but that's a separate issue)

sdolan
Yes, the original code is pretty much an object lesson in why it's a bad idea to use bare exceptions.
Daniel Roseman