开发者

Form doesn't accept additional parameters

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 'pare开发者_开发问答nt' when I'm pretty sure that it is possible to send additional parameters to form's __init__ (ie here : Simple form not validating). 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)


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)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜