例如,我有以下代码:
from django.db import models
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.views.generic import FormView
class MyModel(models.Model)
owner = models.ForeignKey(User)
description = models.TextField()
class MyForm(ModelForm):
class Meta:
model = MyModel
def save(self, owner, commit=True):
self.instance.owner = owner
return super().save(commit)
class MyView(FormView):
success_url = '/'
form_class = MyForm
template_name = 'my_template.html'
def form_valid(self, form):
form.save(self.request.user)
return super().form_valid(form)
如果我在该代码上运行pylint,则会出现以下错误:
[W0221(arguments-differ), MyForm.save] Arguments number differs from overridden 'save' method
这样做是不好的做法?我应该在视图owner
方法中设置form_valid
吗?
答案 0 :(得分:1)
查看文档:{{3}}
为什么不用commit = False调用save,而不是使用不同的签名;这将返回模型实例。然后,您可以添加适当的属性(在本例中为所有者),并直接保存模型。