This question already has an answer here:
I have the following:
from django.contrib.auth.models import User
class ClientDetails(models.Model):
created_by = models.ForeignKey(User)
...
How do I make created_by
default to the currently logged in user?
(I want to do this so I can hide it in the admin view mainly but also because when I save an instance I don't want to be filling it every time)
Since you need to get the currently logged in user from a
request
object you cannot get it in the model'ssave
-method,but you can eg override the model admin'ssave_model
-method:Normal modelfields have a default argument. But ForeignKeys do not as far as I know, so I guess you need to work with a post_save signal.
I had a similar issue recently, this is from my views.py file
And then I had a form for the 'circles' model, which was just a wrapper really (forms.py)
Remember to import the form in your view!
Edit: not even sure if you even need to bother with the separate form, the key bit is the fake commit, followed by the real
You have to override
get_changeform_initial_data
method in your model Admin class inadmin.py
as follows:In such way you obtain the most elegant solution since the
created_by
field is filed up when you create new record.I found:
from here. But isn't there an easier way?
Building on the accepted answer, if you're looking to do this with Class Based views, you can follow the instructions in the docs, overriding the
form_valid()
method on the class view: