Welcome back. Today we will be discussing how to use the admin feature of Django and how to create Django models.
Launch your server. From the last article, you shd have this page up and running.
To the end of the url, add "/admin/". This page should come up:
Now we need to create our admin credentials so that we can log in. Basically we need to create a new superuser.
python manage.py createsuperuser
Fill in the details, and create your new superuser.
Go back to the login page and fill in the credentials you just created.
Click on users and see the details you just created
CREATE A MODEL
The idea of DJANGO Models is that instead of writing everything afresh we can write models which will automatically be transformed into tables by Django
Go to "models.py" and let's create a new model class which we will call 'User'. Note that the first letter is capitalized to indicate that its a class.
from django.db import models
# Create your models here.
class User(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField()
comment = models.TextField()
You can go to the official documentation to learn more about model fields
Next
python manage.py migrate
then
python manage.py makemigrations
You shd notice a new file created(0001_initial.py) within your migrations folder.
Then run again:
python manage.py migrate
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=100)),
('last_name', models.CharField(max_length=100)),
('email', models.EmailField(max_length=254)),
('comment', models.TextField()),
],
),
]
Notice all the new fields we created.
Lastly we need to alert django admin to the presence of a new model. Within "admin.py" add:
from django.contrib import admin
from date_app.models import User
# Register your models here.
admin.site.register(User)
Run the server again, and within it, you shd have a new "User" model within the date_app
Click on "add" and notice the four fields we created within the models.
Now try creating different user objects and saving them
Congratulations, we have just learnt how to use the Django admin and how to create models.
Top comments (0)