set current user value in Django admin for Foreign Key

714 views
Skip to first unread message

Akshay Mukadam

unread,
Dec 10, 2014, 8:38:48 AM12/10/14
to django...@googlegroups.com
Hi,
I just want to show the current logged in user in for foreign key in Django admin. Following are the approach used buy me:

1-> def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "user":
            "set the current user as a default value for drop down"
            kwargs["initial"] = request.user.id
        return super(ResponseAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

2->def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "user":
            "Filter the drop down as per standard procedure"
            kwargs["queryset"] = User.objects.filter(username = request.user.username)
        return super(ResponseAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

Problems for 1st approach is the current logged in user gets properly set but it also shows the other users in the existing database. That is actually wrong because the current user may select the other user name and post the data in  admin.

Problem for second appraoch(For my Team Manager not me) the only logged in user gets populated and user has to select his name. He is unagreed with this scenario neither ok with the 1st solution(neither me).

Is there any other way to solve this

Vijay Khemlani

unread,
Dec 10, 2014, 12:13:27 PM12/10/14
to django...@googlegroups.com
Hmmm... why are you showing the user field in the first place? I would exclude it from the form and set it programatically after the user as submitted the form.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e6d4a7c9-4201-46c3-baaf-1c6f156764ab%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Collin Anderson

unread,
Dec 11, 2014, 3:31:12 PM12/11/14
to django...@googlegroups.com
Hi,

I agree excluding it from the form is the way to go and setting it in one of the save_* methods.

But, couldn't you also do _both_ of your methods :)

Collin
Reply all
Reply to author
Forward
0 new messages