views:

19

answers:

1

How do I prepopulate an Admin field from logged-in User info?

I have model.py:

from django.db import models  
class News(models.Model):  
    title = models.CharField(max_length=65)  
    body = models.TextField()  
    author = models.CharField(max_length=55)  

and I have admin.py:

from django.contrib import admin
from django.contrib.auth.models import User
from newsite.news.models import News
class NewsAdmin(admin.ModelAdmin):
    list_display = ('title','author')
    search_fields = ['title', 'author']
    prepopulated_fields = {'author': (?????)} 
admin.site.register(News, NewsAdmin)

I have been struggling trying to figure out how to get the currently logged-in user into that prepopulated_field for author.

Any tips would be appreciated. Thanks.

+1  A: 

My models.py is this:

author = models.ForeignKey(User)

Admin.py is this:

class BugAdmin( admin.ModelAdmin ):
    fields = ['name', 'slug', 'summary', 'categories', 'status', 'browser', 'frequency', 'really_bug']
    exclude = ('author','excerpt')
    prepopulated_fields = { 'slug' : ['name'] }
    form = BugForm

    def save_form(self, request, form, change):
    obj = super( BugAdmin, self).save_form(request, form, change)
    if not change:
        obj.author = request.user
    return obj
meder
Note that he/she is pulling the data from the request object. (obj.poster = request.user) The request object is, coincidentally, generated first upon every request.
Andrew Sledge
Thanks very much for the tip. One more question:
Kevin
You have form = BugForm. So have you overrided the default form from Admin? Do you have a forms.py that you could share as an example? Thanks.
Kevin
Here you go: http://static.arounds.org/admin-new.txt
meder
Worked nicely. Sweet. Thanks.
Kevin