2010-10-26 124 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()