views:

1110

answers:

2

How can I set a default value on a ForeignKey field in a django Model or AdminModel?

Something like this (but of course this doesn't work)...

created_by = models.ForeignKey(User, default=request.user)

I know I can 'trick' it in the view, but in terms of the AdminModel it doesn't seem possible.

+1  A: 

If you are using the development version of Django, you can implement the formfield_for_foreignkey() method on your AdminModel to set a default value.

Steef
Thanks for the heads up. I'll be looking into that.
T. Stone
A: 

See this blog post. Your question isn't clear as to whether you want the user to be able to override the default selection - if you do, then this might not be of much use.

There's also this blog post, which talks about auto-populating foreign key fields, but again, this is talking about non-overridable methods for setting the value of a foreign key field.

Dominic Rodger
I had seen the 2nd blog post, but the 1st one was exactly what I was looking for.
T. Stone