Djangoでショッピングカートを作りたい1

Vagrant, Amazon Linux2, dbはmysql8系を使います。

$ python3 –version
Python 3.7.9
$ pip3 –version
pip 21.0.1 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)
$ pip3 install Django
$ pip3 install PyMySQL

### プロジェクト作成
$ django-admin startproject shoppingcart
$ cd shoppingcart
$ tree
.
├── manage.py
└── shoppingcart
├── __init__.py
├── asgi.py
├── settings.py
├── urls.py
└── wsgi.py

1 directory, 6 files

setting.py

ALLOWED_HOSTS = ["192.168.33.10"]
// 省略

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'shoppingcart',
        'USER': 'hoge',
        'PASSWORD': 'fuga',
        'HOST': 'localhost',
        'PORT': '3306',
    }
    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': BASE_DIR / 'db.sqlite3',
    # }
}

mysql> create database shoppingcart;
Query OK, 1 row affected (0.03 sec)

__init__.py

import pymysql
pymysql.install_as_MySQLdb()

initpyでimportしないと、mysqlclientをインストールしたかと聞かれるので注意が必要

$ python3 manage.py runserver 192.168.33.10:8000
$ python3 manage.py startapp shop

settings.py

INSTALLED_APPS = [
    'shop',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

### テストコード作成
$ pip3 install pytest-django

$ touch pytest.ini
$ rm shop/tests.py
$ mkdir shop/tests
$ touch shop/tests/test_views.py

pytest.ini

[pytest]
DJANGO_SETTINGS_MODULE = shoppingcart.settings
python_classes = *Test
python_functions = test_*
python_files = tests.py test_*.py *_tests.py
 
norecursedirs = static templates env

shop/tests/test_views.py

from django.test import TestCase

class ViewTest(TestCase):

	def test_first_page(self):
		response = self.client.get('/')
		assert response.status_code == 200

$ pytest -l -v -s shoppingcart && flake8
============================= test session starts ==============================
platform linux — Python 3.8.5, pytest-6.2.3, py-1.10.0, pluggy-0.13.0 — /usr/bin/python3
cachedir: .pytest_cache
django: settings: shoppingcart.settings (from ini)
rootdir: /home/vagrant/prd/dev/shoppingcart, configfile: pytest.ini
plugins: django-4.2.0
collected 0 items

============================ no tests ran in 0.05s =============================

model

class Category(models.Model):
	name = models.CharField(max_length=250, unique=True)
	slug = models.SlugField(max_length=250, unique=True)
	description = models.ImageField(upload_to='category', blank=True)

	class Meta:
		ordering = ('name',)
		verbose_name = 'category'
		verbose_name_plural = 'categories'

	def __str__(self):
		return '{}'.format(self.name)

$ python3 manage.py makemigrations shop
$ python3 manage.py migrate

class Product(models.Model):
	name = models.CharField(max_length=250, unique=True)
	slug = models.SlugField(max_length=250, unique=True)
	description = models.TextField(blank=True)
	category = models.ForeignKey(Category, on_delete=models.CASCADE)
	price = models.DecimalField(max_digits=10, decimal_places=2)
	image = models.ImageField(upload_to='product', blank=True)
	stock = models.IntegerField()
	available = models.BooleanField(default=True)
	created = models.DateTimeField(auto_now_add=True)

	class Meta:
		ordering = ('name',)
		verbose_name = 'product'
		verbose_name_plural = 'products'

	def __str__(self):
		return '{}'.format(self.name)