Create an application
python manage.py startapp app_name
basic structure:
- admin.py – You can register models to include in the Django administration site – this is optional and you may not need to use this in your application.
- apps.py – This file contains main configuration for the current application.
- migrations – This directory contains database migration for the application. Migrations allow Django to track model changes.
- models.py – This file includes the data models for the application. All Django application requires models.py file but the content can be blank.
- tests.py – Any unit tests that applies to the application.
- views.py – The business logics for the application needs to go here. Each view will receive an Http request and process it then generates a return response.
Data models
A Django model will contain data that you need for the application. The model is a Python class that subclass django.db.models.Model. Each model will map to a single database table, and each attribute in the class will map to a database field. Django contain vast amount of methods that can help you query the database object.
For model reference document, use the following link
Common Data Field Types from Django
models.CharField(max_length=250) – VARCHAR in database.
models.SlugField(max_length=250) – VARCHAR in database.
models.TextField() – TEXT column in SQL database.
models.DateTimeField(defeault=timezone.now) – DATETIME column in SQL database. timezone.now will return timezone aware format for database storage. Some other attribute include (auto_now_add=True), etc.
Activating application
To activate application in Django project, go to settings.py and update INSTALLED_APPS field. I could look like the following:
INSTALLED_APPS = [‘django.contrib.admin’,
‘django.contrib.auth’, …
‘app_name.apps.AppNameConfig’, ]
User model
Django comes with authentication framework built in. It is the django.contrib. auth package and it contains User model. You can use User model in models.py and gain access to users registered to Django site.
No responses yet