Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for user ForeignKey with Django admin

author = models.ForeignKey(User)

Is there any way I can set the default value of this field to automatically select the logged in user? I know you can do this in the save method but my client has requested that it automatically defaults to the logged in user at edit time to avoid confusion.

This article goes into how to update it during save, just not at edit time.

like image 860
Hanpan Avatar asked Apr 12 '11 09:04

Hanpan


People also ask

Can a foreign key have a default value?

Yes, you can define a column with a default value of 0 as a Foreign Key. However, for the constraint to work, you would need to have a row in the source table with a value of 0 as well. Example: CREATE TABLE dbo.

What is ForeignKey Django models?

Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.

What is AutoField in Django?

According to documentation, An AutoField is an IntegerField that automatically increments according to available IDs. One usually won't need to use this directly because a primary key field will automatically be added to your model if you don't specify otherwise.

What is Related_name in Django?

The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set. Syntax: field_name = models.Field(related_name="name")


1 Answers

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'author':
            kwargs['initial'] = request.user.id
        return super(MyModelAdmin, self).formfield_for_foreignkey(
            db_field, request, **kwargs
        )
like image 128
Danny W. Adair Avatar answered Sep 29 '22 14:09

Danny W. Adair