4

在从管理界面使用 Notes 时,我希望能够在 Note 中包含对当前经过身份验证的用户的引用。该模型看起来像:

from django.db import models
from django.contrib.auth.models import User
from datetime import datetime



class Note(models.Model):
    datetime = models.DateTimeField(default=datetime.now)
    author   = models.ForeignKey(User, default=authenticated_user)
    note     = models.TextField()

    def __unicode__(self):
        return unicode(self.author) + u' - ' + unicode(self.datetime)

用户应该看到的唯一字段是注释文本字段。日期时间和作者应该由模型、管理界面或其他任何东西自动填写。这可以做到吗?有人有一些示例代码吗?

谢谢!

4

1 回答 1

4

The setting of the date can be taken care of by specifying auto_now_add=True to the datetime field definition.

To set the user on save in the admin, do this in your admin class:

class NoteAdmin(admin.ModelAdmin):
    ...usual admin options...

    def save_model(self, request, obj, form, change):
        obj.user = request.user
        obj.save()
于 2009-05-13T21:53:34.027 回答