0

我更改了 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'))
4

1 回答 1

1

您试图进入userBaseModelForm.save(),但您从未将用户传递给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)
        ...

此外,您可能想传入super(ChildForm, self).save(commit=commit, ...)ChildForm:

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

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

于 2020-03-03T09:51:39.187 回答