Tuesday, December 3, 2019

Dissecting the DJango Polls app



To check if Django is installed
python3 -m django --version

To create the project, below is the command. A project contains auto-generated code that establishes a Django project which is a collection of settings for an instance of Django, including database configuration, Django-specific options and application-specific settings.


django-admin startproject mysite

Below given some details about the project

mysite => Container for the project
manage.py => Command line utility that lets one to interact with the project
mysite/__init__.py => This indicates that the project should be considered as project
mysite/settings.py => Settings/configuration of Django project
mysite/urls.py => The URL declarations for Django project. Kind of ToC for the Django project
mysite/wsgi.py => An Entry point for WSGI compatible web servers to serve the project

Now to run the server, switch to mysite directory and run the below command
http://127.0.0.1:8000/

python3 manage.py runserver

Now to change the port where the app is running, commands can be as below

python3 manage.py runserver 8080

Now, an app is something that comes under a project.
An app can live anywhere in the project path, but for simplicity, it could be in parallel to the manage.py

python3 manage.py startapp polls


Now this creates a polls folder and adds a few files. Now to define the view, below to be done

polls/views.py

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

Now we need to give a mapping to the view, which can be done in the urls. This file is called URLConf file for an application, and in this cases, urls.py is created to copy the below contents.

polls/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

Now we need to link the polls application to the mysite and that can be done via the urls module like below

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

The site will now be accessible via http://127.0.0.1:8000/plls by default

Now below is how we setup the database part

The database easiest choice is SQLite3. This can be seen in the mysite/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

The name of your database. If using SQLite, the database will be a file on your computer; in that case, NAME should be the full absolute path, including filename, of that file. The default value, os.path.join(BASE_DIR, 'db.sqlite3'), will store the file in your project directory.


In the settings file, there are a few installed apps, they are like this below

django.contrib.admin : Admin site
django.contrib.auth : Auth framework
django.contrib.contenttypes  : framework for content types
django.contrib.sessions : session framework
django.contrib.messages : Messaging framework
django.contrib.staticfiles : Framework for managing static files


Now some of these applications might be using the databases internally, os we need to run the below migrate command to create table for these

python3 manage.py migrate


This command looks a the installed apps settings and create any necessary database tables according to the database settings in the mysite/settings.py


Now we need to create models in the app

inside the polls/models.py, we need to add below piece of information

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

This helps the Django framework for doing the below things

Create a database schema (CREATE TABLE statements) for this app.
Create a Python database-access API for accessing Question and Choice objects.


Now we need to include the app inside the project, to do that polls.py/PollsConfig to be included in to the installed apps folder

Now we need to run make migration command

python3 manage.py makemigrations polls

This tells the Django that we have made some changes in the Models and that needs to be reflected in the databases and stored as migration

Below command will return the SQL scripts which will run when running the migrate command.

python manage.py sqlmigrate polls 0001


The exact command may vary depending on the data base in use.
The table name is chosen automatically by combining the app name and the model name
By convention, Django appends "_id" to the foreign key field name. (Yes, you can override this, as well.)

Now we need to create these models in database, for this, we need to do the below

python3 manage.py migrate

The migrate command takes all the migrations that haven’t been applied (Django tracks which ones are applied using a special table in your database called django_migrations) and runs them against your database - essentially, synchronizing the changes you made to your models with the schema in the database


Now there is a python shell that comes with Django API

python3 manage.py shell



References:
https://docs.djangoproject.com/en/2.2/intro/tutorial01/

No comments:

Post a Comment