In this tutorial, we will explore the Django admin interface, a powerful tool that Django provides out-of-the-box for managing the data in your application. We'll learn how to set up the admin interface, how to create a superuser who can access this interface, and how to make your application's models manageable from the admin interface.
By the end of this tutorial, you will be able to:
- Enable and access the Django admin interface
- Create a Django superuser
- Register your models with the Django admin interface
To follow along with this tutorial, you should have some basic knowledge of Python and Django, including how to create a Django project and define models.
The Django admin interface is enabled by default in every Django project. To access it, you need to first start your Django development server with the command:
python manage.py runserver
Then, open your web browser and navigate to http://localhost:8000/admin
.
Before you can log in to the Django admin interface, you need to create a superuser - a user with control over everything in the application. This can be done using the following command:
python manage.py createsuperuser
You will be prompted to enter a username, email (optional), and password for the superuser.
To manage your models from the Django admin interface, you need to register them. This can be done in the admin.py
file in your application directory. For example, to register a model named MyModel
, you would do:
from django.contrib import admin
from .models import MyModel
admin.site.register(MyModel)
When you run the createsuperuser
command, you will see something like this:
Username: admin
Email address: admin@example.com
Password: ******
Password (again): ******
Superuser created successfully.
Now, you can log in to the Django admin interface with the username and password you entered.
Consider a Django application named blog
, with a model named Post
. To register this model with the admin interface, you would write in blog/admin.py
:
from django.contrib import admin
from .models import Post
admin.site.register(Post)
Now, when you log in to the Django admin interface, you will see Posts
listed in the BLOG
section on the main admin page.
In this tutorial, we learned how to enable and access the Django admin interface, how to create a superuser, and how to register models with the admin interface. The next step in your learning journey could be exploring the various ways to customize the Django admin interface, such as changing the displayed fields, adding filters, or customizing the form widgets.
For the first exercise, remember that the createsuperuser
command will prompt you to enter a username, email, and password. For the second exercise, you will need to create a new model in your models.py
file, then register it in admin.py
using admin.site.register(YourModel)
. For the third exercise, use the Django admin interface to interact with your models.