[PYTHON] From 0 to Django development environment construction to basic operation

Since it is a memorandum & personal use, it is written quite simply. I think beginners should also refer to other articles.

Version note

I mainly worked with python 2.7.10 and Django 1.6. Please note the following points when working with python 3 series, Django 1.9

Select the appropriate version when $ pyenv install Select the appropriate version when $ pip install django. (The latest 1.9 is included by default)

It feels like a database is created in one shot after writing a model with Django 1.6 $ python manage.py syncdb. After writing the model as 1.9 After making a migration file with $ python manage.py makemigrations app name It feels like creating a DB from a migration file with $ python manage.py migrate.

That's it (probably).

1. Environment construction

1-1. Install pyenv

Install from GitHub

$ git clone https://github.com/yyuu/pyenv.git ~/.pyenv

(~ / .pyenv is the local directory name. Make it an appropriate name) Write pyenv settings to zshenv, bash_profile, etc.

export PYENV_ROOT=$HOME/.pyenv
export PATH=$PYENV_ROOT/bin:$PATH
eval "$(pyenv init -)"

(Rewrite $ HOME to the installation location of pyenv as appropriate) Restart Shell for the settings to take effect.

$ exec $SHELL

1-2. Installing python

Install python from pyenv.

$ pyenv install 2.7.10

Set the installed version.

$ pyenv global 2.7.10
$ pyenv rehash

Verification

$ pyenv versions
* 2.7.10 (set by /hoge/.pyenv/version)

1-3. Django installation and test project creation

Install Django 1.6 from pip

$ pip install django==1.6

Create test project

$ django-admin.py startproject mysite

Server startup

$ cd mysite
$ python manage.py runserver

Go to http: // localhost: 8000 and check if the server is running.

2. Django test project

2-1. Basic usage

Main References Creating your first Django app, part 1 | Django 1.4 Documentation

Editing the configuration file (setting.py)

Change the settings related to DB. By default, sqlite is used, but this time PostgreSQL is used. See Notes on enabling PostgreSQL with Django | Qiita It is assumed that a new user and database are created by installing the postgresql library etc. referring to the above site.

setting.py

DATABASES = {
    'default': {
        # 'ENGINE': 'django.db.backends.sqlite3',
        # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mysite',
        'USER': 'djangouser',
        'PASSWORD': 'pass',
        'HOST': '127.0.0.1',
        'PORT': 5432,
    }
}

Creating a table

Create the table used by the application described in INSTALLED_APPS in setting.py by executing the following command.

$ python manage.py syncdb

(The syncdb command looks for the INSTALLED_APPS setting and creates the required table on the database according to the database settings in settings.py.)

Creating an application

$ python manage.py startapp polls

(Polls is the application name)

Creating a model

polls/models.py


from django.db import models

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

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()

Make your project aware of polls apps

Rewrite the settings to make the project aware of the polls app. Added polls inside ╩╗INSTALLED_APPS`.

setting.py


INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'polls',
)

Display SQL from the created model

$ python manage.py sql polls
BEGIN;
CREATE TABLE "polls_poll" (
    "id" serial NOT NULL PRIMARY KEY,
    "question" varchar(200) NOT NULL,
    "pub_date" timestamp with time zone NOT NULL
)
;
CREATE TABLE "polls_choice" (
    "id" serial NOT NULL PRIMARY KEY,
    "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id") DEFERRABLE INITIALLY DEFERRED,
    "choice" varchar(200) NOT NULL,
    "votes" integer NOT NULL
);
COMMIT;

Issue SQL statement from model and write to DB

$ python manage.py syncdb

Play Django's API in Python's interactive shell

See Creating your first Django app, part 1 | Django 1.4 Documentation rather than playing with the API.

Launch a python interactive shell.

$ python manage.py shell

(Let's play variously with reference to the above site)

By the way, in the process of playing, polls / models.py was rewritten as follows.

polls/models.py


import datetime
from django.utils import timezone
from django.db import models

class Poll(models.Model):

    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __unicode__(self):
        return self.question

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):

    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()

    def __unicode__(self):
        return self.choice

Recommended Posts

From 0 to Django development environment construction to basic operation
Django development environment construction memo
django project development environment construction
Python development environment construction 2020 [From Python installation to poetry introduction]
[For beginners] Django -Development environment construction-
From Ubuntu 20.04 introduction to environment construction
Django environment construction
django environment construction
[Google App Engine] Flow from development environment construction to application creation
Django project environment construction
From Kivy environment construction to displaying Hello World
Python development environment construction
python2.7 development environment construction
From Python environment construction to virtual environment construction with anaconda
[Memo] Django development environment
Django development using virtualenv Procedures from virtual environment construction to new project / new application creation and initial settings
Procedure to exe python file from Ubunts environment construction
Docker + Django + React environment construction
[MEMO] [Development environment construction] Python
[MEMO] [Development environment construction] wine
[AWS] I tried using EC2, RDS, Django. Environment construction from 1
From environment construction to deployment for flask + Heroku with Docker
Deploy Django + React from scratch to GKE (1) Backend development --Nginx + Django
Procedure from environment construction to operation test of testinfra, a server environment test tool made by Python
Mac + Eclipse (PyDev) + Django environment construction
[Django] Memorandum of environment construction procedure
[Python3] Development environment construction << Windows edition >>
Python development environment construction on macOS
[MEMO] [Development environment construction] Jupyter Notebook
Emacs Python development environment construction memo
Ubuntu Desktop 20.04 development environment construction memo
Development environment construction (2020 version, WSL2 + VcXsrv)
pynq-z1 From purchase to operation check
Deep learning tutorial from environment construction
Django development environment construction with Docker-compose + Nginx + uWSGI + MariaDB (macOS edition)
LINEbot development, I want to check the operation in the local environment
From PyCUDA environment construction to GPGPU programming on Mac (MacOS 10.12 Sierra)
Mac OS X Mavericks 10.9.5 Development environment construction
Python (anaconda) development environment construction procedure (SpringToolsSuites) _2020.4
WEB application development using django-Development environment construction-
[Python] Road to snake charmer (1) Environment construction
Python3 + venv + VSCode + macOS development environment construction
Procedure from AWS CDK (Python) development to AWS resource construction * For beginners of development
Get started with Python in 30 minutes! Development environment construction & learn basic grammar
Mac OS X Yosemite 10.10 Development environment construction
Mac OS X development environment construction memo
Construction of development environment for Choreonoid class
Windows + gVim + Poetry python development environment construction
[Basic] Unify everything from tabulation to dashboard creation! Data visualization application development with Python and Dash ~ Overview of Dash, environment construction, sample execution ~
pynq-z1 From purchase to operation check
Did not change from Python 2 to 3
From ROS for Windows installation to operation check
From 0 to Django development environment construction to basic operation
Sum from 1 to 10
How to create an article from the command line
Let's add it to the environment variable from the command ~
Python local development environment construction template [Flask / Django / Jupyter with Docker + VS Code]
Let's try TensorFlow music generation project "Magenta" from development environment setting to song generation.
Collecting information from Twitter with Python (Environment construction)
Introduction to Python Let's prepare the development environment
Build Django + NGINX + PostgreSQL development environment with Docker
Build the fastest Django development environment with docker-compose
Until Django application creation by terminal (development environment)
[Python] Build a Django development environment with Docker
[Remotte Development] Switch from administrator mode to developer mode
Kotlin / Native development environment construction & installation procedure & tutorial
From ROS for Windows installation to operation check