I have a model (UserProfile) with which I want to record a user’s IP address when new user accounts are created.
I’ve begin the process of overriding the Django model’s save() method, but I am totally uncertain how to properly access HttpRequest attributes from within a model. Can any of you guys help? Google was unable to provide a specific answer for me.
You always need to pass on request information from the view to your save-method.
Consider that saving an instance doesn’t always have to be invoked from a http request (for a simple example think of calling
savein the python shell).If you need to access the
requestobject within the admin while saving, you can override it’ssave_modelmethod:But otherwise you always have to pass it on from the view:
Or to make this easier to re-use, make a method on the model like:
and call it from your view with
obj.foo(request).