Instructions to create django app – P2

Tram Ho

Part 2 – Create project, create app, create model, migration, admin page


  • Create the app

  • Create views in the app
  • Create url in app
  • Put the url of the app into the project

Database setup mysite/settings.py :

1 of 4 types of ENGINE:

  • ‘django.db.backends.sqlite3’
  • ‘django.db.backends.postgresql’ ( py-postgresql package), ‘django.db.backends.postgresql_psycopg2’ (package psycopg2 ) …
  • ‘django.db.backends.mysql’
  • ‘django.db.backends.oracle’ Demo default config

Need to use additional environment borders, demo with python-dotenv package:

=>

Creating models

Basically django support creates migration database file based on model declaration => is better than laravel, rails ✌️

Demo polls/models.py :

Activating models

At mysite/settings.py : add INSTALLED_APPS polls configuration 'polls.apps.PollsConfig'

CMD: python manage.py makemigrations polls => create automatic migration file from models (Question, Choice)

Check migration sql at runtime: python manage.py sqlmigrate polls 0001 => run file 0001 to create tables in the database.

Migrate database: python manage.py migrate

Using API shell

Open django shell interactive: python manage.py shell Create data with rice:

Because <QuerySet [<Question: Question object (1)>]> not convenient for __str__ is necessary to use __str__ :

Refer to the use of datetime and timezone, the commands to add, edit, delete, query, filter with django shell: https://docs.djangoproject.com/en/3.0/intro/tutorial02/

Introducing the Django Admin

Looking at migrated tables from the outset, Django Admin is a very powerful support mechanism for basic CRUD management when no new spec is required. Django automatically creates an administration interface for models. Site management uses the site to add news, sporting events … Django solves the problem of creating a unified interface for site administrators to edit content. The administrator is not intended to be used by site visitors, but to webmasters.

Creating an admin user

create new administrator: python manage.py createsuperuser Start server => python manage.py runserver to admin login page, but can’t manage app polls

Making app polls editable by admin page

polls/admin.py :

Share the news now

Source : Viblo