I'm doing some stuff on 'clean' on an admin ModelForm:
class MyAdminForm(forms.ModelForm):
def clean(self):
# Some stuff happens...
request.user.message_set.create(message="Some stuff happened")
class MyAdmin(admin.ModelAdmin):
form = MyAdminForm
Other than the threadlocals hack - how do I access request.user to set a message? I can't pass it to the form constructor because doesn't get called from my code.
You can't do it on the form without passing the user into the form constructor. Instead you can use the
ModelAdmin.save_model
function which is given the request object.http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model
Edit: Since you want to put the logic/messages in the clean function you could do something like:
Very late edit:
user.message_set
is set to be deprecated in Django 1.4. You should instead useModelAdmin.message_user
. https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.message_userYou would have to explicitly pass it there in constructor, which isn't a thing, that is usually done.
Are you sure you want to put that stuff into a form? What exactly you would like to do there? Isn't raising
ValidationError
enough?