Version 19 (modified by rajeshdhawan, 7 years ago) (diff)

Used formset.model instead of

How to set the current user on the model instance in the admin (newforms-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 PostModelAdmin(admin.ModelAdmin):

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

    def save_model(self, request, obj, form, change): 

        instance =

        instance.user = request.user


        return instance

    def save_formset(self, request, form, formset, change): 

        def set_user(instance):
            instance.user = request.user

        if formset.model == Comment:
            instances =
            map(set_user, instances)
            return instances
            return, PostModelAdmin)

Back to Top