Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign currently logged in user as default value for a model field?

Tags:

I'd like to do something like this:

class Task(models.Model):     ...     created_by = models.ForeignKey(User, **default=[LoggedInUser]** blank=True, null=True, related_name='created_by') 

Is this possible? I couldn't find what's the proper way to get the logged in user, apart from doing request.user, in a view, which doesn't seem to work here.

PS_ I realise I could initialize the Model data by other means, but I think this is the cleanest way.

like image 938
Nacho Avatar asked Mar 10 '10 04:03

Nacho


1 Answers

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() 
like image 98
scaraveos Avatar answered Oct 05 '22 10:10

scaraveos