我知道这是一篇旧帖子,但以防万一有人到达这里,这是我的解决方案,受Django 启发:如何在管理表单中获取当前用户:
模型.py:
class Comment(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey("content_type", "object_id")
user = models.ForeignKey(User)
content = models.TextField()
time = models.DateTimeField(auto_now_add=True)
管理员.py:
class CommentInlineForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CommentInlineForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.pk:
self.fields['content'].widget.attrs['readonly'] = True
class CommentInlineFormset(BaseGenericInlineFormSet):
def save_new(self, form, commit=True):
setattr(form.instance, "user", self.current_user)
return super(CommentInlineFormset, self).save_new(
form, commit=True)
class CommentInline(GenericTabularInline):
model = Comment
extra = 1
form = CommentInlineForm
formset = CommentInlineFormset
readonly_fields = ('user', 'time')
def has_delete_permission(self, request, obj=None):
return False
def get_formset(self, request, obj=None, **kwargs):
formset = super(CommentInline, self).get_formset(
request, obj, **kwargs)
formset.current_user = request.user
return formset
注1:这里的关键是覆盖GenericTabularInline.get_formset()传入request.user,并用它来填充BaseGenericInlineFormSet.save_new()中的“user”字段。以便正确记录登录用户。其他代码只是为了使它更像“评论”。例如,只读字段,不删除等。
注2:这是一个通用的解决方案,所以无论我们要评论哪个模型,只需添加
inlines = [CommentInline,]
到管理班,我们很高兴。