我更改了 Django 表单中的保存方法。然后我从该方法继承了另一个保存方法,并对子方法进行了一些更改,这发生了冲突。我不知道如何解决冲突,以便我对父方法的其他使用保持健康并且不会被宠坏。
表格.py
class BaseModelForm(forms.ModelForm):
def save(self, commit=True, **kwargs):
"""
Save this form's self.instance object if commit=True. Otherwise, add
a save_m2m() method to the form which can be called after the instance
is saved manually at a later time. Return the model instance.
"""
if self.errors:
raise ValueError(
"The %s could not be %s because the data didn't validate." % (
self.instance._meta.object_name,
'created' if self.instance._state.adding else 'changed',
)
)
if commit:
# If committing, save the instance and the m2m data immediately.
self.instance.save(user=kwargs.pop('user'))
self._save_m2m()
else:
# If not committing, add a method to the form to allow deferred
# saving of m2m data.
self.save_m2m = self._save_m2m
return self.instance
class ChildForm(BaseModelForm):
def save(self, commit=True, **kwargs):
new_instance = super(ChildForm, self).save(commit=True)
# Some other codes goes here!
return new_instance
模型.py
class BaseFieldsModel(models.Model):
def save(self, *args, **kwargs):
user = kwargs.pop('user', None)
if user:
if self.pk is None:
self.created_by = user
self.updated_by = user
super(BaseFieldsModel, self).save(*args, **kwargs)
视图.py
def my_view(request,id):
if form.is_valid():
instance = form.save(commit=False)
# Some codes goes here!
instance.save(user=request.user)
错误是:
KeyError at /my/url
Request Method: POST
'user'
Exception Type: KeyError
Exception Value:
'user'
And Django Debug page separately highlight these three lines:
instance = form.save(commit=False)
new_instance = super(ChildForm, self).save(commit=True)
self.instance.save(user=kwargs.pop('user'))