GE03 ‐ 1 ‐ Models, Migrations, and the Admin page (David Jones) - wycre/CS3300-Team-2-9 GitHub Wiki
Models
Models are essentially the classes that define the information stored in the database.
Read more on Models:
- TODO add link to field types
- TOOD add link to model relationships
Migrations
Migrations update the schema of the database so that objects can be stored that align with the defined models.
If django warns you that there are unapplied migrations, simply run python3 manage.py migrate to apply the migrations.
Migrations are stored in a folder called migrations/, you won't need to interact with the items in this folder, but they will be committed to git.
After making changes to the models, you will need to make new migrations before applying them:
python3 manage.py makemigrations portfolio_app
python3 manage.py migrate portfolio_app
It is best practice to include the app name portfolio_app as we only intend to make changes to the portfolio_app migrations.
The Admin page
The admin page will exist at the /admin path.
Before you can access the admin page, you will need to create a superuser in the database so that you can log in. Run the following command:
python manage.py createsuperuser
This command will create an interactive shell and will ask for a username, email, and password for the new superuser account. After you enter all the information you can run the server and login to the admin page using the account you just created.
Registering models for Admin
If you want to create new objects in the admin interface you will need to register their models in the portfolio_app/admin.py file.
First you need to add an import statement for each model, for example:
from portfolio_app.models import Student
Then you need to register it using the admin.site.register method, for example:
admin.site.register(Student)
A good practice is to create a ModelAdmin for each Model you include. This allows you to include custom fields and values specific to the admin interface. For example:
class StudentAdmin(admin.ModelAdmin):
pass # Define custom values and fields here
admin.site.register(Student, StudentAdmin)
If the default admin interface works well, this is not necessary, but it is good practice to include them to make the code more extensible for the future.