views:

36

answers:

1

I have attached TestInline in the FoobarAdmin, this thing works well but i want logged in user to be pre-populated for the added_by field

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

class Test(models.Model):

    description = models.TextField()
    added_on = models.DateTimeField(auto_now_add=True)
    added_by = models.ForeignKey(User, related_name='added_by',)

class TestInline(admin.TabularInline):
        model = Test
        extra = 1

class FoobarAdmin(admin.ModelAdmin):
    inlines = [TestInline,]

admin.site.register(Foobar, FoobarAdmin)

Please let me know if its possible to have user prepopulated for the added_by field

+1  A: 

See prepopulated_fields in the admin docs.

If I understand what you need correctly, I think this article by James Bennett tackles the issue pretty well.

Finally (in case you haven't seen them), there are two other informative posts on prepopulating admin fields.

Dave Everitt
I already checked but the problem is added_by field is a foreignKey to user and the docs says "prepopulated_fields doesn't accept DateTimeField, ForeignKey, nor ManyToManyField fields."Can you please help me out of this?
Suhail
Seems the favoured way is to override the relevant admin form with one that uses Javascript/JQuery to do what you need. There are several StackOverflow posts on this, and here is one that seems most useful: http://stackoverflow.com/questions/2799857/filtering-foreign-keys-with-ajax-in-django-admin
Dave Everitt
However (and I haven't tried this, so just wondering) perhaps you could try using 'default' instead: http://docs.djangoproject.com/en/dev/ref/models/fields/#default
Dave Everitt
Did you read Bennett's article? http://www.b-list.org/weblog/2008/dec/24/admin/
Dave Everitt