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's save
-method,but you can eg override the model admin's save_model
-method:
class MyAdmin(admin.ModelAdmin):
def save_model(self, request, instance, form, change):
user = request.user
instance = form.save(commit=False)
if not change or not instance.created_by:
instance.created_by = user
instance.modified_by = user
instance.save()
form.save_m2m()
return instance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With