form doesn't allow editing
I have a following form:
class PlayForwardPageForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PlayForwardPageForm, self).__init__(*args, **kwargs)
class Meta:
开发者_Python百科 model = PlayForwardPage
exclude = ( 'id',)
def save(self, *args, **kwargs):
post = super(PlayForwardPageForm, self).save(*args, **kwargs)
post.save()
and view that shows it :
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)
When loading page everything works fine. But when I try to save the form with changed data I get:
'data' is an invalid keyword argument for this function
Can anyone see any reason or this behavior ?
Short answer: PlayForwardPage
is a model not a ModelForm
.
Here's the corrected code, with some extra style comments.
# 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)
Also, you're doing some unnecessary things in your 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()
精彩评论