我有很多具有user
字段的对象,我想用当前用户自动填充该字段。为此,我有一个mixin
class AttachUserMixin(object):
def save_model(self, request, obj, form, change):
"""
При сохранении модели присвоить ему текущего юзера
"""
obj.user = request.user
obj.save()
但是,在我的一些模型表单中,我有一些当前用户的验证,如下所示:
def clean(self):
data = super(ListForm, self).clean()
if data['type'] == ListTypes.ctr0.value:
existing_lists = (List.objects
.filter(country=data['country'],
user=data['user'],
ad_network=data['ad_network'],
type=data['type'])
.exclude(pk=self.instance.pk)
.all())
如果我从模型表单中删除user
字段,那么事情显然会崩溃。那么如何从clean
内访问当前用户?
答案 0 :(得分:1)
我回答一个例子:
class X_Form(forms.ModelForm):
def __init__(self,request,*args,**kwargs):
super(X_Form, self).__init__(*args,**kwargs)
self.request = request
def clean(self):
user = self.request.user
...
和观点
def post_method(request):
form = X_Form(data=request.POST or None,request=request)
...
当然,如果我理解正确你的意思