Build a web application with Django

This is Qiita's first post. I used to develop a web application using Django as an internship, but I had never created it from scratch, so I tried to start the server.

Premise

Environment

Build a development environment.

terminal


$ brew install pyenv pyenv-virtualenv mysql
$ pyenv install 3.5.1
$ pyenv global 3.5.1
$ pyenv virtualenv 3.5.1 django-sample-3.5.1

$ mysql.server start

Creating a Django application

The directory structure is as follows. When I looked it up, there were many configurations where I created a folder with the project name / project name and added local apps under it.

django-sample


.
├── README.md
├── manage.py
├── libs
│   └── #Library is included with pip install
├── requirements.txt
├── templates
│   ├── common
│   │   └── _base.html
│   └── home
│       └── index.html
└── django-sample
    ├── settings.py
    ├── urls.py
    └── views.py

There seems to be a command that automatically generates it, but this time I did it manually.

terminal


$ mkdir django-sample
$ cd django-sample
$ pyenv local django-sample-3.5.1

Write the required libraries in requirements.txt.

requirements.txt


django==1.11
django-extensions==1.7.8
mysqlclient==1.3.10

You can install it normally, but I wanted to put it under the project like Rails vendor / bundle, so install it under ./libs.

terminal


$ pip install -r requirements.txt -t libs

Edit manage.py.

manage.py


import os
import sys

# ./Pass the libs path
sys.path.append(os.path.join(os.path.dirname(__file__), 'libs'))

settings_module_name = os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django-sample.settings')

if __name__ == '__main__':
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

Edit settings.py. The database user name, password, etc. are set in environment variables. Creation of databases, users, etc. is omitted. Since I tried the login function etc., it may contain settings that are not necessary this time.

django-sample/settings.py


import os


ROOT_PATH = os.path.dirname(os.path.dirname(__file__))

DEBUG = os.getenv('DJANGO_SAMPLE_BEBUG')

ALLOWED_HOSTS = [
    'localhost'
]

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.sessions',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django_extensions'
]

MIDDLEWARE_CLASSES = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware'
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': os.getenv('DJANGO_SAMPLE_DATABASE_HOST'),
        'NAME': os.getenv('DJANGO_SAMPLE_DATABASE_NAME'),
        'USER': os.getenv('DJANGO_SAMPLE_DATABASE_USER'),
        'PASSWORD': os.getenv('DJANGO_SAMPLE_DATABASE_PASSWORD')
    }
}

SESSION_COOKIE_NAME = 'djangosample'
SECRET_KEY = os.getenv('DJANGO_SAMPLE_SECRET_KEY')
CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN'
CSRF_SESSION_NAME = 'csrf'
CSRF_COOKIE_SECURE = True
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'

ROOT_URLCONF = 'django-sample.urls'

LOGIN_REDIRECT_URL = '/'

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(ROOT_PATH, 'static')
]

SITE_ID = 1

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(ROOT_PATH, 'templates')
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',
                'django.template.context_processors.i18n',
                'django.template.context_processors.request',
                'django.template.context_processors.static'
            ]
        }
    }
]

Migrate the database.

terminal


$ python manage.py migate

Define the View class.

django-sample/views.py


from django.views.generic import TemplateView


class HomeView(TemplateView):
    template_name = 'home/index.html'

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        return context

home_view = HomeView.as_view()

Edit the template displayed in the browser.

templates/home/index.html


{% extends 'common/_base.html' %}

{% block content %}
  <h1>Hello World!!</h1>
{% endblock %}

templates/common/_base.html


<!DOCTYPE html>
<html>
<head>
  <title>django-sample</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>

Finally, set the routing.

django-sample/urls.py


from django.conf import settings
from django.conf.urls import include, url

from . import views


urlpatterns = [
  # /
  url(r'^$', views.home_view)
]

Launch the server and go to [http: // localhost: 8000](http: // localhost: 8000).

terminal


$ python manage.py runserver

Finally

This code is also posted on Github. https://github.com/yukidallas/django-sample

Next time, I will post about the implementation of login function (email registration, Twitter login).

Recommended Posts

Build a web application with Django
I made a WEB application with Django
Web application creation with Django
Deploy a Django application with Docker
[Python] A quick web application with Bottle!
Run a Python web application with Docker
If you know Python, you can make a web application with Django
Build a Flask / Bottle-like web application on AWS Lambda with Chalice
Launched a web application on AWS with django and changed jobs
[Python] Build a Django development environment with Docker
Build a Django environment with Vagrant in 5 minutes
Build a Django development environment with Doker Toolbox
Create a one-file hello world application with django
Quickly build a Python Django environment with IntelliJ
Web application development with Flask
Create a homepage with django
Web application with Python + Flask ② ③
Real-time web with Django Channels
Web application with Python + Flask ④
Looking back on creating a web service with Django 1
(Python) Try to develop a web application using Django
Launch a Python web application with Nginx + Gunicorn with Docker
Looking back on creating a web service with Django 2
Web application made with Python3.4 + Django (Part.1 Environment construction)
Build a machine learning application development environment with Python
A memo about building a Django (Python) application with Docker
Build a development environment with Poetry Django Docker Pycharm
Build a Django environment for Win10 (with virtual space)
The story of making a web application that records extensive reading with Django
Try creating a web application with Vue.js and Django (Mac)-(1) Environment construction, application creation
Create a web application that recognizes numbers with a neural network
WEB application development using Django [Django startup]
Creating a web application using Flask ②
WEB application development using Django [Application addition]
Measure Django application coverage with Coverage.py
[Memo] Build a development environment for Django + Nuxt.js with Docker
Build a deb file with Docker
Creating a voice transcription web application
Django Tips-Create a ranking site with Django-
Twitter posting application made with Django
[Django] Build a Django container (Docker) development environment quickly with PyCharm
Build a bulletin board app from scratch with Django. (Part 2)
Build a speed of light web API server with Falcon
Build a bulletin board app from scratch with Django. (Part 3)
Creating a web application using Flask ①
Make a filter with a django template
Create a web API that can deliver images with Django
Create a Todo app with Django ① Build an environment with Docker
(For beginners) Try creating a simple web API with Django
Creating a web application using Flask ③
Deploy a Django application on EC2 with Nginx + Gunicorn + Supervisor
Creating a web application using Flask ④
Create a file uploader with Django
Let's make a WEB application for phone book with flask Part 1
Web App Development Practice: Create a Shift Creation Page with Django! (Shift creation page)
Let's make a WEB application for phone book with flask Part 2
Let's make a WEB application for phone book with flask Part 3
Let's make a WEB application for phone book with flask Part 4
[DynamoDB] [Docker] Build a development environment for DynamoDB and Django with docker-compose
WEB application development using Django [Model definition]
Easily build a development environment with Laragon