2

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

jimwan
  • 1,086
  • 2
  • 24
  • 39

1 Answers1

7

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

YardenST
  • 5,119
  • 2
  • 33
  • 54
  • Thanks for your reply, can you answer more detail since i am new. – jimwan Nov 28 '12 at 14:27
  • def save_model(self, request, obj, form, change): obj.user = request.user obj.save() in thie function, how can i set the Task.Creator? – jimwan Nov 28 '12 at 14:28
  • Now i have another question, that i want the Task model to show by filter by fefault, not by click the filter option which is set in modelAdmin like this:class TaskAdmin(admin.ModelAdmin): list_display = ['Name','Owner','EstEndTime','LastModifiedTime','Statu'] search_fields = ['Name'] list_filter=('Statu','Project',DecadeByOwer,) – jimwan Nov 28 '12 at 15:14
  • @jimwan I didn't understand, but if it is another question, start a new question, instead of us talking in comments :) – YardenST Nov 28 '12 at 15:18
  • @YadenST, ok,this is the link for that question http://stackoverflow.com/questions/13599359/dont-want-show-all-items-of-a-model-object-in-django . in that question, i have success to filter by the model.Manager, but i can only filte by a certain user rather that the current user. can you tell me how to improve that to make the Task object items not show all tasks but the current user's tasks. – jimwan Nov 28 '12 at 16:00