Version 7 (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/models.py

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

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

# app/admin.py

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

class PostModelAdmin(admin.ModelAdmin):

    fields= ('content',)

    def __call__(self, request, url):

        self.user = request.user

        return super(PostModelAdmin, self).__call__(request, url)

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

        new_object = form.save(commit=False)

        new_object.user = self.user
        new_object.save()

        form.save_m2m()
        
        return new_object

admin.site.register(Post, PostModelAdmin)


Back to Top