Version 9 (modified by oyvind, 7 years ago) (diff)


How to set the current user on the model instance using newforms admin.

TODO make it work with inline edited models

# 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, form, change): 

        instance =

        instance.user = request.user

        return instance

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

        instances =

        for instance in instances:

            instance.user = request.user

        formset.save_m2m(), PostModelAdmin)

Back to Top