Auto registering models in Django Admin

Django admin is a very valuable tool for developers especially during the development phase. Normal way of registering a model to the admin is as below.

 

Four lines of code for a single model. Now consider the amount of repeated code required if you have 10 models in your app. It also require you to manually edit the field list when your model changes.   You can get the admin to update the field list automatically if you change the list_display declaration as below.

But you still have to update your admin.py  whenever you add a new model to the app. To automatically register all models in your app, you can use below code snippet. Remember to put it at the end of your admin.py so that your custom ModelAdmin classes will still work as usual.

 

If you  want the auto registration to work only during development(DEBUG mode), you can use the below snippet.

 

You may also like...

Leave a Reply

Your email address will not be published.