django - tetsuyaf1100/hello-world GitHub Wiki

準備

centos7.7の場合、sqlite3.7でエラーになるので、sqlite3最新バージョンにしておく

  • 仮想環境作成とDjangoインストール
cd
python3 -m venv venv
. venv/bin/activate

pip install django

project作成

django-admin startproject mysite
cd mysite

vim mysite/settings.py
ALLOWED_HOSTS = ['*']

python manage.py runserver 0:8000

pollsアプリ作成

python manage.py startapp polls
  • vim polls/views.py
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")
  • vim polls/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
  • vim mysite/urls.py
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]
  • 動作確認
python manage.py runserver 0:8000
curl localhost:8000/polls/

DB設定

  • vim mysite/settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

TemplateView の使用

  • template用意
mkdir -p polls/templates/polls

vim polls/templates/polls/index.html

{{message}}
  • vim mysite/settings.py
    templateのパスが見つけられるように、polls.apps.PollsCOnfig追加
    pollsアプリ(ディレクトリ)のapps.pyファイルのPollsConfigクラスを追加
INSTALLED_APPS = [
     'polls.apps.PollsConfig',
  • vim polls/views.py
from django.shortcuts import render
from django.views import View
from django.views.generic import TemplateView

class IndexView(TemplateView):
    template_name = 'polls/index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['message'] = 'hello_index_page!!'
        return context
index = IndexView.as_view()
  • 動作確認
python manage.py runserver 0:8000
curl localhost:8000/polls/

モデルを作成する

vim polls/models.py

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)

モデルを有効にする

vim mysite/settings.py   
INSTALLED_APPS = [
     'polls.apps.PollsConfig',

python manage.py makemigrations polls
python manage.py sqlmigrate polls 0001
python manage.py migrate

api

python manage.py shell
Python 3.6.8 (default, Nov 16 2020, 16:55:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from polls.models import Choice, Question
>>> Question.objects.all()
<QuerySet []>
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
>>> q.save()
>>> q.id
1
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2021, 10, 15, 8, 49, 39, 561322, tzinfo=<UTC>)
>>> q.question_text = "What's up?"
>>> q.save()
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>
  • vim polls/models.py
import datetime
from django.db import models
from django.utils import timezone

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question_text
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text
  • api
python manage.py shell

>>> from polls.models import Choice, Question
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')
<QuerySet [<Question: What's up?>]>
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>

>>> Question.objects.get(id=2)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/root/django-lessons/myenv/lib64/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/root/django-lessons/myenv/lib64/python3.6/site-packages/django/db/models/query.py", line 437, in get
    self.model._meta.object_name
polls.models.Question.DoesNotExist: Question matching query does not exist.

>>> Question.objects.get(pk=1)
<Question: What's up?>
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True
>>> q = Question.objects.get(pk=1)
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: Not much>]>
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
>>> c.question
<Question: What's up?>
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: Not much>, <Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()
5
>>> Choice.objects.filter(question__pub_date__year=current_year)
<QuerySet [<Choice: Not much>, <Choice: Not much>, <Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
(1, {'polls.Choice': 1})

管理ユーザ作成

python manage.py createsuperuser
  • 動作確認
python manage.py runserver localhost:8000

lynx localhost:8000/admin/
  • pollsアプリ追加
vim polls/admin.py

from django.contrib import admin
from .models import Question
admin.site.register(Question)

補足

  • error
ModuleNotFoundError: No module named 'matplotlib'

pip install matplotlib

⚠️ **GitHub.com Fallback** ⚠️