Developers usually do not have interactive access to the database on the production server, even with the Python console. How can you manipulate the data in the database? Can your colleagues do anything with business objects if they don't know Python and Django?
You're probably dreading having to write yet another web interface for that. Well, it's not all that bad: you'll need to write some code, but not as much as you think. Django provides a helpful admin interface to work with objects in it.
Registering models
You don't have any models in the admin interface as a start. To add one, register them in the admin.py module. This module exists in each application by default.
Let's look at a hypothetical project. We are creating an online auction but do not have much time to prepare the first release. To avoid using external dependencies, we change the site's content in the Django admin interface. The models look like this:
from django.contrib.auth.models import User
from django.db import models
class Lot(models.Model):
description = models.CharField(max_length=256)
initial_price = models.FloatField()
class Bid(models.Model):
lot = models.ForeignKey(Lot, on_delete=models.CASCADE)
price = models.FloatField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
To see models in the admin interface, register them with the register function. Let's see what we should add to the admin.py module.
from django.contrib import admin
from .models import Bid, Lot
admin.site.register(Bid)
admin.site.register(Lot)
We've registered our models. Now let's see what you can get from it.
Admin interface
Admins are not ordinary users; they are superusers in Django terminology. To use the interface, create a superuser account if you don't have one already. Also, do not remove path('admin/', admin.site.urls) from the default configuration of the main urls.py module of your project.
If you're done with all preparations, run python manage.py runserver from the console and go to the http://localhost:8000/admin URL in your browser. You should log in with a superuser account.
Now you can add, change or delete Users, Groups, Bids, and Lots. Try to check out every link and change the objects you want; it will help you familiarize yourself with the interface.
All objects in the database have a page, and you can see and change the object's content.
You already know how to fill the content of the service through the web interface. Let's now learn how to upgrade it and add restrictions and modifications.
is_staff attribute is responsible for access to the administrative part of the site, so any user whose is_staff value is True can access the admin areaCustomize fields
Not all data should be open for changes. For example, our clients won't be happy if we adjust their bids. No matter how honest developers and business users are, it's better not to let them change any data in the Bid objects. To customize fields, use the ModelAdmin class.
The instance of the ModelAdmin class has a lot of customizable attributes. The fields attribute is the list of model fields you want to display on a page. The readonly_fields is the list of fields that all admins can see but not modify. Both attributes can be tuple or list instances.
class BidAdmin(admin.ModelAdmin):
fields = ('lot', 'price', 'user')
readonly_fields = ('lot', 'price', 'user')
admin.site.register(Bid, BidAdmin)
Now you can check that you see all the data but cannot modify any bids. You can choose what to include on a page by removing some elements from the list.
readonly_fields attribute should be a subset of the fields attribute; otherwise, not all elements from read-only fields will be on a page.ModelAdmin classes.Additional fields
It's great to get the plain data from the tables with several lines of code, but how do we add more information from the database?
We want to see which lots are trending. In our case, it's the lots with ten bids or more. There is no such field in a model, but we can prepare the ModelAdmin field with this value. Choose any name you want unless it intersects with the existing attribute of the class. For more info, take a look at the attributes in the documentation. We've added the trending method with the string trending to the fields list:
class LotAdmin(admin.ModelAdmin):
fields = ('description', 'initial_price', 'trending')
readonly_fields = ('trending',)
def trending(self, obj):
return '🔥' if obj.bid_set.count() >= 10 else '❄'
After you've added the custom field, you can see if a lot is trending. Besides strings, a method may return any other Python objects converting them to strings implicitly.
readonly_fields list; otherwise, it will produce an error. Custom fields are not modifiable.Inline admin field
We can add any fields we like if they are custom values or parts of a model. We can also use the inline fields to display all the bids for a lot on the page.
This time, create an additional class for displaying each inline object. You want to add bids to a page with the lot, so create the TabularInline class for the Bid model:
from django.contrib import admin
from .models import Bid, Lot
class BidInline(admin.TabularInline):
can_delete = False
model = Bid
readonly_fields = ('price', 'user')
class LotAdmin(admin.ModelAdmin):
inlines = (BidInline,)
admin.site.register(Lot, LotAdmin)
We don't register the BidInline class because we cannot use it independently, but we define the model attribute for it. Restrict the actions for this class with read-only fields and set can_delete attribute to False to prevent deleting bids by the admin user.
In the LotAdmin class, define the inlines attribute and add the BidInline to it.
That's it; all bids with the lot item are displayed on the same page.
There are many options available for you to modify default classes, and you can read more about it in the official documentation.
Sorting and ordering
Our app became popular, and we now have hundreds of lots and bids. When administrators open their list, it's easy for them to get confused, and finding the right lot or bid is tough. To fix the situation, you can use the sorting of available items.
The Django admin interface provides a way to sort and order objects using the list_display and ordering attributes in the ModelAdmin class. list_display specifies which fields are displayed in the list of objects, and the order in which they are displayed can be used to sort the list. ordering specifies the default order in which objects are displayed and can be used to sort the list by one or more fields. Together, these attributes provide a flexible way to customize the display and ordering of objects in the admin interface.
from django.contrib import admin
from .models import Bid
class BidAdmin(admin.ModelAdmin):
list_display = ('lot', 'price', 'user')
ordering = ('-price',)
admin.site.register(Bid, BidAdmin)
As you can see, we can add the - symbol before the field name to sort the objects by their price in reverse order.
Conclusion
The Django admin interface is a powerful and flexible tool that simplifies managing website data. By customizing fields, adding extra fields, and using inline admin fields, developers can create an intuitive and efficient administrative environment tailored to the specific needs of their applications. By leveraging these features, one can enhance productivity and streamline the overall management of a Django project.