0
1

Django - ローカル開発環境構からテンプレート表示まで

Posted at

環境構築

terminal
python3 -m venv venv

source venv/bin/activate

python -m pip install --upgrade pip

pip install django

pip freeze > requirements.txt

django-admin startproject core .

python manage.py startapp website

設定ファイルの編集

settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'website'
]

TIME_ZONE = 'Asia/Tokyo'

LANGUAGE_CODE = 'ja'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'sample',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

MySQLを使用

terminal
pip install mysqlclient

mysql.server start

mysql -uroot 

DBの作成

mysql
create database sample;

マイグレーションとスーパーユーザー作成

terminal
python manage.py makemigrations

python manage.py migrate  

python manage.py createsuperuser

URL、views、template設定

core/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('website.urls')),
    path('admin/', admin.site.urls),
]
website/urls.py
from django.urls import path
from .views import index

urlpatterns = [
    path('', index, name='index'),
]
website/views.py
from django.shortcuts import render

def index(request):
    return render(request, 'website/index.html', {})
website/templates/website/index.html
<html>
    hello world
</html>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1