How to access inputed values of model fields before creation in Django admin dashboard
Hello, in this post I am going to show you how you can access the inputed values of model fields in django admin dashboard before it is created.
I'll explain the steps to you using a practical example. Lets say you have an Author model as shown below
class Authors(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
email = models.EmailField()
def __str__(self):
return self.name
Due to one or more reasons you want to be able to access the value from the fields inputed by the user before the Author object is created. To achieve this follow the steps below;
- Go to your apps admin.py and create a new admin class as shown below
class AuthorAdmin(admin.ModelAdmin):
model = Author
def save_model(self, request, obj, form, change):
print(obj.user)
print(obj.name)
print(obj.email)
super().save_model(request, obj, form, change)
What this does is print out the values inputed into the field in the admin dashboard before saving. You can do a whole lot here like for example, lets say you want to automatically add an extra name to the one inputed by the user, all you have to do to achieve that is to modify your code in the save_model method as shown below;
class AuthorAdmin(admin.ModelAdmin):
model = Author
def save_model(self, request, obj, form, change):
obj.name = obj.name + ' maester'
super().save_model(request, obj, form, change)
This will add an extra name to whatever is inputed by the user (e.g if the user inputs dan, the name will be saved as dan maester in the database).
Conclusion
Through this post we have been able to learn how we can access and manipulate the data inputed in a model field before the model object is created. As alwasy thanks for reading and leave a comment down below if you have any and I will reply you as soon as I can.