Reputation: 1136
First i am sorry for asking this question, i am a new user for django. And i set up my project only by the models.Model
##models.py
class Task(models.Model):
Name = models.CharField('Title', max_length=200)
Notes = models.TextField('Description',max_length=2000, null=True)
Creator = models.ForeignKey(User, related_name='TaskCreator', null=True, blank=True)
def __unicode__(self):
return self.Name
##admin.py
class TaskAdmin(admin.ModelAdmin):
list_display = ['Name', 'Owner','EstEndTime','LastModifiedTime','Statu']
admin.site.register(Task,TaskAdmin)
I use the django's default admin for my site, i don't use any template of myself. now when a user log in and is going to create a task, i want to set the creator default by the current user. But i don't know how to get the current user in the models.Model. I have looked up some information from the network, such as http://chewpichai.blogspot.tw/2007/09/using-user-info-outside-request-in.html, but it can not work. So who can tell me the method of getting current user in models.py file without the request. It preplexs me for a long time, i really wish someone can help me. Thanks
Upvotes: 2
Views: 4363
Reputation: 5256
You need to override the save_model
in the Admin Class.
class TaskAdmin(admin.ModelAdmin):
list_display = ['Name', 'Owner','EstEndTime','LastModifiedTime','Statu']
def save_model(self, request, task, form, change):
task.Creator = request.user
task.save()
read about it here https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model
Upvotes: 7