T. Stone T. Stone - 1 month ago 6
Python Question

How do you specify a default for a Django ForeignKey Model or AdminModel field?

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.

Answer

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.