从 Django 中的其他 save() 方法继承时,表单 save() 方法发生冲突

Conflict in form save() method when inherit from other save() method in Django

我更改了 Django 中的保存方法 form.Then 我从该方法继承了另一个保存方法并对子方法进行了一些更改,但发生了冲突。我不知道如何解决冲突,以便我对父方法的其他使用保持健康并且不会被宠坏。

Forms.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

Models.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)

Views.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'))

您试图在 BaseModelForm.save() 中获取 user,但您从未将用户传递给 form.save() 调用。您需要添加 form.save(..., user=request.user):

def my_view(request,id):
    ...
    instance = form.save(commit=False, user=request.user)

并在 super(ChildForm, self).save(..., **kwargs)

中传递
class ChildForm(BaseModelForm):
    def save(self, commit=True, **kwargs):
        new_instance = super(ChildForm, self).save(commit=True, **kwargs)
        ...

此外,您可能想在 ChildForm 中传递 super(ChildForm, self).save(commit=commit, ...)

new_instance = super(ChildForm, self).save(commit=True, **kwargs)

因为否则形式 class 可能不尊重从视图传递的提交标志(当然,除非您已经在省略的代码中处理了它)。