Skip to content
Advertisement

Django, link a model field with an admin model field with ForeignKey

I’m trying to link a “normal” model field with an admin model field, for example I have a table “Post” and I want to add the admin username as a ForeignKey to the field “Author” of the table Post.

I mean :

JavaScript

Where admin.username refers the username of auth_user admin model

Thanks for your help

Advertisement

Answer

As the referencing the user model section of the documentation says, you can make use of settings.AUTH_USER_MODEL to obtain a reference to the user model that is used. You can use the to_field=… [Django-doc] to specify to what field of the model it should refer, so:

JavaScript

By specifying editable=False [Django-doc] it will not automatically show up in ModelForms.

In views, you can then set the logged in user as author by specifing the author attribute. For example:

JavaScript

Note: A ForeignKey does not store the string representation (or name) of the referenced object in the column, it stores the primary key of the record it references in a column with an _id suffix to a ForeignKey field. Therefore ForeignKeys usually do not end with a _name suffix. You might want to consider renaming the username field to author.

Advertisement