Reputation: 8710
I have a lot of objects that have a user
field which I want to be populated automatically with current user. For this, I have a mixin
class AttachUserMixin(object):
def save_model(self, request, obj, form, change):
"""
При сохранении модели присвоить ему текущего юзера
"""
obj.user = request.user
obj.save()
However, in some of my model forms I have some validation by current user, like this:
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())
If I remove the user
field from the model form, the thing obviously crashes. So how do I access current user from within clean
?
Upvotes: 0
Views: 469
Reputation: 734
i answer with an example:
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
...
and in views
def post_method(request):
form = X_Form(data=request.POST or None,request=request)
...
Of course, If I understand correctly you mean
Upvotes: 1