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.

 

Author
author-image

Hello, my name is Abubakar Zakari. Am a budding fullstack developer from Nigeria who loves developing softwares and learning new frameworks and langauges.

Comment

Select image


Comments
No comment yet

DEVMAESTERS

Newsletter

Services

Frontend Development |Backend Development |Full Website Development |Bootstrap Website upgrades | Website Debbugging | Website Hosting & deployment

Contact

Interested in hiring me or collaborating with me on a project, click on any of the links below to get my social media handle

Or contact me via Tel: (+234)-806-225-7480 | Email: abubakarzakari1703@gmail.com

Copywright@devmaesters.com
Privacy Policy

By using our website,
you agree that devmaesters can store cookies on your device and disclose information in accordance with our privacy policy.