How to assign currently logged in user as default value for a model field?
No, you can't do it this way. Django (and Python) has pretty much zero global values, and that's a Good Thing(tm). Normally you get the current user in the view(request)
with request.user
. You can then pass that as a param to various methods/functions, but trying to set a global user
will only lead to tears in a multi-threaded environment.
There should be a bumper sticker that says, Globals are Evil. This will give you a good idea about my Number One problem with PHP.
If you want to achieve this within the admin interface, you can use the save_model method. See below an example:
class List(models.Model):
title = models.CharField(max_length=64)
author = models.ForeignKey(User)
class ListAdmin(admin.ModelAdmin):
fields = ('title',)
def save_model(self, request, obj, form, change):
obj.author = request.user
obj.save()