Django admin auto assign field on model save
Hello, In this post I am going to show you how you can automatically assign a value to a field on model save in django admin dashboard.
Lets say for example you have an article model like the one below
class Article(models.Model):
user = models.ForeignKey(User, related_name="article_user", on_delete=models.CASCADE)
title = models.CharField(max_length=100)
body = models.TextField()
pub_status = models.BooleanField(default=False)
created_date = models.DateTimeField()
updated_date = models.DateTimeField()
def __str__(self):
return str(self.title)
What we want in this scenerio is that the user field in the Article model should
- Be hidden from everyone
- Automatically be assigned to the current logged in user when a new artile is created
To achieve this all thats needed is to go to your admin.py and create a new admin class like so
class ArticleAdmin(admin.ModelAdmin):
model = Article
def save_model(self, request, obj, form, change):
obj.user = request.user
super().save_model(request, obj, form, change)
exclude = ['user']
What this does is create a custom article admin class within which we are using the save model method to automatically assign the user field to the current logged in user whenever a new aricle is created.
Finally register your custom article class like so
admin.site.register(Article, ArticleAdmin)
This is not restricted to the user field alone, we can do the same thing for any field in our model by following the steps above.
Conclusion
In conclusion through the method above we have been able to setup a way to automatically assign values to fields on model creation in django admin dashboard. As always thanks for reading and feel free to leave any questions or comments down below.