Thursday, September 17, 2020

To create model/tables in db and register that in admin page

 Create a model class and it will be synced to backend database.


To create tables in db with the objects in models.py (ORM)

dependency package:

pip install pillow

pillow package required for images.

courses\models.py

from django.db import models

class Course(models.Model):
 image = models.ImageField(upload_to='images/')
 summary = models.CharField(max_length=200)

 def __str__(self):#string representation of an object.this method used for.
   return self.summary

You can add predefined choices also to pick while creating database data.And some other parameters as you can see below.

demo\models.py
--
from django.db import models
class Book(models.Model):
 BOOKS={
  ('HB','Hobbit'),
  ('LOTR','Lord of the Rings')
 }
STATUSES={
   (0,'Unknown'),
 (1,'processed'),
 (2,'paid')
}
 title=models.CharField(max_length=36)#null=False,blank=True,unique=True,default='',choices=BOOKS,choices=STATUSES



python manage.py makemigrations courses-->appname
--to store changes to models in DB schema.
--we need to do this everytime there is change in model,like adding new fields.
--this will create the template ready, for below command.The migrations folder will be created and kept here the migrations.
python manage.py migrate

-------------------
create a super user in admin page:
---
default app imported to support admin site is django.contrib.admin
and a url pattern already added.
python manage.py createsuperuser
to login <rooturl>/admin


To register our model of courses app to admin page:
courses\admin.py

 
from .models import Course
admin.site.register(Course)

Then, it will be visible in the admin page.

No comments:

Post a Comment