django - 使用 FormView 和 ModelForm 更新模型 [英] django - update model with FormView and ModelForm
问题描述
我不知道如何在 FormView
中使用 ModelForm
来更新已经存在的实例??
I can't figure out how to use a ModelForm
in a FormView
so that it updates an already existing instance??
表单在此 URL 上发布:r'/object/(?P<pk>)/'
The form POSTs on this URL: r'/object/(?P<pk>)/'
我使用 ModelForm
(而不是直接使用 UpdateView
),因为其中一个字段是必需的,我对其进行了清理.
I use a ModelForm
(and not directly an UpdateView
) because one of the fields is required and I perform a clean on it.
我基本上想在 FormView
(在 POST)中初始化表单时提供 kwarg instance=...
以便它绑定到其pk 在 url 中给出.但我不知道在哪里做...
I'd basically like to provide the kwarg instance=...
when initializing the form in the FormView
(at POST) so that it's bound to the object whose pk is given in the url. But I can't figure out where to do that...
class SaveForm(ModelForm):
somedata = forms.CharField(required=False)
class Meta:
model = SomeModel # with attr somedata
fields = ('somedata', 'someotherdata')
def clean_somedata(self):
return sometransformation(self.cleaned_data['somedata'])
class SaveView(FormView):
form_class = SaveForm
def form_valid(self, form):
# form.instance here would be == SomeModel.objects.get(pk=pk_from_kwargs)
form.instance.save()
return ...
推荐答案
在与您讨论之后,我仍然不明白您为什么不能使用 UpdateView
.如果我理解正确的话,这似乎是一个非常简单的用例.您有一个要更新的模型.并且您有一个自定义表单可以在将其保存到该模型之前进行清洁.似乎 UpdateView
可以正常工作.像这样:
After some discussion with you, I still don't see why you can't use an UpdateView
. It seems like a very simple use case if I understand correctly. You have a model that you want to update. And you have a custom form to do cleaning before saving it to that model. Seems like an UpdateView
would work just fine. Like this:
class SaveForm(ModelForm):
somedata = forms.CharField(required=False)
class Meta:
model = SomeModel # with attr somedata
fields = ('somedata', 'someotherdata')
def clean_somedata(self):
return sometransformation(self.cleaned_data['somedata'])
class SaveView(UpdateView):
template_name = 'sometemplate.html'
form_class = SaveForm
model = SomeModel
# That should be all you need. If you need to do any more custom stuff
# before saving the form, override the `form_valid` method, like this:
def form_valid(self, form):
self.object = form.save(commit=False)
# Do any custom stuff here
self.object.save()
return render_to_response(self.template_name, self.get_context_data())
当然,如果我误解了你,请告诉我.不过,您应该能够让它发挥作用.
Of course, if I am misunderstanding you, please let me know. You should be able to get this to work though.
这篇关于django - 使用 FormView 和 ModelForm 更新模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!