Version 22 (modified by Florian Apolloner, 11 years ago) (diff)


How to set the current user on the model instance in the admin:

# app/

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

class Post(models.Model):
    user = models.ForeignKey(User)
    content = models.TextField()

class Comment(models.Model):
    post = models.ForeignKey(Post)
    user = models.ForeignKey(User)
    content = models.TextField()

# app/

from app.models import Post, Comment
from django.contrib import admin

class CommentInline(admin.TabularInline):
    model = Comment
    fields = ('content',)

class PostAdmin(admin.ModelAdmin):

    fields= ('content',)
    inlines = [CommentInline]

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

    def save_formset(self, request, form, formset, change): 
        if formset.model == Comment:
            instances =
            for instance in instances:
                instance.user = request.user
  , PostAdmin)

Back to Top