Version 14 (modified by oyvind, 16 years ago) ( diff )

--

How to set the current user on the model instance in the admin (newforms-admin)

# 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()

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

# app/admin.py

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_form(self, request, form, change): 

        instance = form.save(commit=False)

        instance.user = request.user
       
        return instance

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

        instances = formset.save(commit=False)

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

        if formset.__name__ == 'CommentInline':
            return map(set_user, instances)
        else:
            return instances

admin.site.register(Post, PostModelAdmin)


Note: See TracWiki for help on using the wiki.
Back to Top