views:

170

answers:

3

Hi all,

I have a database of articles with a

submitter = models.ForeignKey(User, editable=False)

Where User is imported as follows:

from django.contrib.auth.models import User. 

I would like to auto insert the current active user to the submitter field when a particular user submits the article.

Anyone have any suggestions?

A: 

As per http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields you can't use ForeignKey with the prepopulated_field admin directive, alas

But this thread might help you. In my answer I also link to a Google-scanned version of Pro Django, which has a great solution for this kind of thing. Ideally, am sure it's better if you can buy the book, but Google seems to have most of the relevant chapter anyway.

stevejalim
I can't really see the relevant pages...
FurtiveFelon
A: 

Just in case anyone is looking for an answer, here is the solution i've found here: http://demongin.org/blog/806/

To summarize: He had an Essay table as follows:

from django.contrib.auth.models import User

class Essay(models.Model):
    title = models.CharField(max_length=666)
    body = models.TextField()
    author = models.ForeignKey(User, null=True, blank=True)

where multiuser can create essays, so he created a admin.ModelAdmin class as follows:

from myapplication.essay.models import Essay
from django.contrib import admin

class EssayAdmin(admin.ModelAdmin):
    list_display = ('title', 'author')
    fieldsets = [
        (None, { 'fields': [('title','body')] } ),
    ]

    def save_model(self, request, obj, form, change):
        if getattr(obj, 'author', None) is None:
            obj.author = request.user
        obj.save()
FurtiveFelon
A: 

If you dont want to keep foregnkey in you model to user.

then in your admin.py override save method

obj.author = request.user.username

obj.save()

this will store the username who is logged in your db

ha22109