如何在Django管理面板中获取当前记录的用户ID?

时间:2011-07-20 10:40:23

标签: django django-models django-admin

我有模型消息,它是表单管理器。要填写“用户”和“组”字段,我需要知道当前记录的用户ID,但我不知道如何在保存之前获取它。

class Message(models.Model):
    title = models.CharField(max_length = 100)
    text = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, null = True, blank = True)
    main_category = models.ForeignKey(MainCategory)
    sub_category = models.ForeignKey(SubCategory)
    groups = models.ManyToManyField(Group)

class MessageAdminForm(forms.ModelForm):
   def __init__(self, *arg, **kwargs):
       super(MessageAdminForm, self).__init__(*arg, **kwargs)  
       self.initial['main_category'] = MainCategory.objects.get(title = 'News')

3 个答案:

答案 0 :(得分:7)

请勿在表单中执行此操作。覆盖管理子类上的save_model方法 - 它可以访问请求。

class MessageAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        obj.user = request.user
        super(MessageAdmin, self).save(request, obj, form, change)

答案 1 :(得分:0)

编辑:丹尼尔的方式更好。

在您看来:

user = request.user
if user.is_authenticated():
    user_id=user.pk # pk means primary key

但是你通常不会处理这个ID。将User字段设置为对象,而不是id。这是我正在处理的事情的片段:

def question_submit(request):
    u = request.user
    if u.is_authenticated():
        if q.is_valid():
            f=q.save(commit=False)
            f.user=u
            f.save()

            return JsonResponse({'success': True})

答案 2 :(得分:0)

避免ERROR --- 'super' object has no attribute 'save' To resolve use ---

使用此:

def save_model(self, request, obj, form, change):
    obj.user = request.user
    super(MessageAdmin, self).save_model(request, obj, form, change)