Version 22 (modified by 13 years ago) ( diff ) | ,
---|
How to set the current user on the model instance in the 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 PostAdmin(admin.ModelAdmin): fields= ('content',) inlines = [CommentInline] def save_model(self, request, obj, form, change): obj.user = request.user obj.save() def save_formset(self, request, form, formset, change): if formset.model == Comment: instances = formset.save(commit=False) for instance in instances: instance.user = request.user instance.save() else: formset.save() admin.site.register(Post, PostAdmin)
Note:
See TracWiki
for help on using the wiki.