How to access request.user from an admin ModelForm

2019-04-09 05:55发布

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.

2条回答
爷的心禁止访问
2楼-- · 2019-04-09 06:35

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.

The save_model method is given the HttpRequest, a model instance, a ModelForm instance and a boolean value based on whether it is adding or changing the object. Here you can do any pre- or post-save operations.

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:

class MyAdminForm(forms.ModelForm):
    user_messages = []
    def clean(self):
        # Some stuff happens...
        user_messages.append("Some stuff happened")

class MyAdmin(admin.ModelAdmin):
    form = MyAdminForm
    def save_model(self, request, obj, form, change):
        for message in form.user_messages:
            request.user.message_set.create(message=message)

Very late edit:

user.message_set is set to be deprecated in Django 1.4. You should instead use ModelAdmin.message_user. https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.message_user

查看更多
叼着烟拽天下
3楼-- · 2019-04-09 06:48

You 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?

查看更多
登录 后发表回答