2010-10-26 121 views
0

我有以下形式:形式不允许编辑

class PlayForwardPageForm(forms.ModelForm):   
    def __init__(self, *args, **kwargs): 
     super(PlayForwardPageForm, self).__init__(*args, **kwargs) 

    class Meta: 
     model = PlayForwardPage 
     exclude = ('id',) 

    def save(self, *args, **kwargs):  
     post = super(PlayForwardPageForm, self).save(*args, **kwargs) 
     post.save() 

和视图,显示它:

object = PlayForwardPage.objects.all()[0] 
form = PlayForwardPageForm(instance=object) 

if request.method == "POST": 
    form = PlayForwardPage(data=request.POST, instance=object) 
    if form.is_valid(): 
     form.save() 
     return HttpResponseRedirect(reverse('manage_playforward',)) 
else: 
    form = PlayForwardPageForm(instance=object) 

当加载网页一切正常。但是,当我试图保存更改的数据形式获得:

'data' is an invalid keyword argument for this function

有人能看到任何理由,这种行为?

回答

1

简答题:是一个模型而不是ModelForm

以下是更正后的代码,以及一些额外的样式注释。

# Don't shadow built-ins (in your case "object") 
play_forward_page = PlayForwardPage.objects.all()[0] 
# Don't need this form declaration. It'll always be declared below. form = PlayForwardPageForm(instance=object) 

if request.method == "POST": 
    # Should be a the form, not the model. 
    form = PlayForwardPageForm(data=request.POST, instance=play_forward_page) 
    if form.is_valid(): 
     form.save() 
     return HttpResponseRedirect(reverse('manage_playforward',)) 
else: 
    form = PlayForwardPageForm(instance=play_forward_page) 

而且,你正在做一些不必要的东西在你的PlayForwardPageForm:

class PlayForwardPageForm(forms.ModelForm):   

# This __init__ method doesn't do anything, so it's not needed. 
# def __init__(self, *args, **kwargs): 
#  super(PlayForwardPageForm, self).__init__(*args, **kwargs) 

    class Meta: 
     model = PlayForwardPage 
     exclude = ('id',) 

# You don't need this since you're not doing anything special. And in this case, saving the post twice. 
# def save(self, *args, **kwargs):  
#  post = super(PlayForwardPageForm, self).save(*args, **kwargs) 
#  post.save()