Voltでフロントを構築する

Github: https://github.com/themesberg/volt-bootstrap-5-dashboard

Fileをvagrantにダウンロードし、Quick Startに沿って構築していきます。
$ tree
97 directories, 2216 files
// npmでgulpをインストールします
$ npm install gulp-cli -g
$ npm install
// node_modulesがインストールされました
$ ls
LICENSE.md README.md gulpfile.js html&css node_modules package-lock.json package.json src

// サーバ起動
$ gulp
http://192.168.33.10:3000/index.html
// ポートが3000番になっている事に留意

コマンドラインでhtml&cssのフォルダに移動するには、&の前にバックスラッシュをつける
$ cd html\&css

これからdashboard中心に編集していきます。

mecabの辞書作成

### CSVファイルを作成
アナと雪の女王,,,1,名詞,一般,*,*,*,*,アナと雪の女王,アナトユキノジョオウ,アナトユキノジョオー

辞書のフォーマット: 表層形,左文脈ID,右文脈ID,コスト,品詞,品詞細分類1,品詞細分類2,品詞細分類3,活用型,活用形,原型,読み,発音

$ sudo mkdir /usr/local/lib/mecab/dic/userdic
$ sudo sudo /usr/lib/mecab/mecab-dict-index \
> -d /usr/local/mecab/dic/ipadic \
> -u /usr/local/lib/mecab/dic/userdic/add.dic \
> -f utf-8 \
> -t utf-8 \
> add_term.csv
dictionary_compiler.cpp(82) [param.load(DCONF(DICRC))] no such file or directory: /usr/local/mecab/dic/ipadic/dicrc

うーん、全然上手くいかんな。。

自然言語処理: mecabの環境構築1

### mecabインストール
$ sudo yum update -y
$ sudo yum groupinstall -y “Development Tools”

$ wget ‘https://drive.google.com/uc?export=download&id=0B4y35FiV1wh7cENtOXlicTFaRUE’ -O mecab-0.996.tar.gz
$ tar xzf mecab-0.996.tar.gz
$ cd mecab-0.996
$ ./configure
$ make
$ make check
$ sudo make install
$ cd –
$ rm -rf mecab-0.996*

$ git clone –depth 1 https://github.com/neologd/mecab-ipadic-neologd.git
$ ./mecab-ipadic-neologd/bin/install-mecab-ipadic-neologd -n -a -y
terminate called after throwing an instance of ‘std::bad_alloc’
what(): std::bad_alloc

$ sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
$ sudo /sbin/mkswap /var/swap.1
$ sudo /sbin/swapon /var/swap.1
$ free

what(): std::bad_alloc

VMのmemoryを4Gにしないと駄目らしい。
面倒なので、focalfossaで開発する

$ sudo apt install mecab
$ sudo apt install libmecab-dev
$ sudo apt install mecab-ipadic-utf8
$ mecab
特急はくたか
特急 名詞,一般,*,*,*,*,特急,トッキュウ,トッキュー
は 助詞,係助詞,*,*,*,*,は,ハ,ワ
く 動詞,自立,*,*,カ変・クル,体言接続特殊2,くる,ク,ク
た 助動詞,*,*,*,特殊・タ,基本形,た,タ,タ
か 助詞,副助詞/並立助詞/終助詞,*,*,*,*,か,カ,カ
EOS

$ git clone https://github.com/neologd/mecab-ipadic-neologd.git
$ cd mecab-ipadic-neologd
$ sudo bin/install-mecab-ipadic-neologd

$ sudo vi /etc/mecabrc

;dicdir = /var/lib/mecab/dic/debian
dicdir = /usr/lib/x86_64-linux-gnu/mecab/dic/mecab-ipadic-neologd

なんかneologdのインストールが上手くいかんな。。。

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

いよいよショッピングカートを作っていきます。
$ python3 manage.py startapp cart

setting.py

INSTALLED_APPS = [
    'shop',
    'search',
    'cart',
    // 省略
]
// 省略
        'DIRS': [os.path.join(BASE_DIR, 'shop', 'templates/'), os.path.join(BASE_DIR, 'search', 'templates/'), os.path.join(BASE_DIR, 'cart', 'templates/')],

cart/models.py

from django.db import models
from shop.models import Product

class Cart(models.Model):
	cart_id = models.CharField(max_length=250, blank=True)
	date_added = models.DateField(auto_now_add=True)

	class Meta:
		db_table = 'Cart'
		ordering = ['date_added']

	def __str__(self):
		return self.cart_id

class CartItem(models.Model):
	product = models.ForeignKey(Product, on_delete=models.CASCADE)
	cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
	quantity = models.IntegerField()
	active = models.BooleanField(default=True)

	class Meta:
		db_table = 'CartItem'

	def sub_total(self):
		return self.product.price * self.quantity

	def __str__(self):
		return self.product.name

$ python3 manage.py makemigrations cart
$ python3 manage.py migrate

cart/urls.py

from django.urls import path
from . import views

app_name = 'cart'

urlpatterns = [
	path('', views.cart_detail, name='cart_detail'),
]

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('shop/', include('shop.urls')),
    path('search/', include('search.urls')),
    path('cart/', include('cart.urls')),
]

cart/views.py
L session.session_keyでセッションの値を取得する

from django.shortcuts import render, redirect
from .models import Cart, CartItem
from django.core.exceptions import ObjectDoesNotExist

def _cart_id(request):
	cart = request.session.session_key
	if not cart:
		cart = request.session.create()
	return cart

def cart_detail(request, total=0, counter=0, cart_items = None):
	try:
		cart = Cart.objects.get(cart_id=_cart_id(request))
		cart_items = CartItem.objects.filter(cart=cart, active=True)
		for cart_item in cart_items:
			total += (cart_item.product.price * cart_item.quantity)
			counter += cart_item.quantity
	except ObjectDoesNotExist:
		pass

	return render(request, 'cart/cart.html', dict(cart_items = cart_items, total = total, counter = counter))

cart/template/cart/cart.html

{% extends "base.html" %}
{% load static %}

{% block metadescription %}
	This is the shopping cart page.. Proceed to review your items and place the order.
{% endblock %}

{% block title %}
	Cart - Various Product Store
{% endblock %}

{% block content %}
	{% if not cart_items %}
	<div>
		<div class="text-center">
			<br>
			<h1 class="text center my_title">Your shopping cart is empty</h1>
			<br>
			<p class="text-center">
				Please click <a href="{% url 'shop:all_product' %}">here</a> to continue shopping.
			</p>
		</div>
	</div>
	{% else %}
	<div>
		<div class="text-center">
			<br>
			<h1 class="text-center my_title">
				Your shopping cart
			</h1>
		</div>
		<br>
	</div>
	<div class="row mx-auto">
		<div class="col-12 col-sm-12 col-lg-6 text-center">
			<table class="table my_custom_table">
				<thread class="my_custom_thread">
					<tr>
						<th colspan="5">
							Your items
						</th>
					</tr>
				</thread>
				<tbody>
					{% for cart_item in cart_items %}
					<tr>
						<td><a href="cart_item.product.get_absolute_url"><img src="{{cart_item.product.image.url}}" alt="" class="float-left rounded custom_image"></a></td>
						<td class="text-left">
							{{cart_item.product.name}}
							<br>
							SKU: {{cart_item.product.id}}
							<br>
							Unit Price: ${{cart_item.product.price}}
							<br>
							Qty: {{cart_item.quantity}} x ${{cart_item.product.price}}
						</td>
						<td>
							${{cart_item.sub_total}}
						</td>
						{% if cart_item.quantity < cart_item.product.stock %}
						<td>
							<a href="{% url 'cart:add_cart' cart_item.product.id %}" class="custom_a"><i class="fas fa-plus-circle custom_icon"></i></a>

							<a href="" class="custom_a"><i class="fas fa-minus-circle custom_icon"></a>

							<a href="" class="custom_item"><i class="far fa-trash-alt"></a>
						</td>
						{% else %}
						<td>
							<a href="" class="custom_a"><i class="fas fa-minus-circle custom_icon"></a>

							<a href="" class="custom_item"><i class="far fa-trash-alt"></i></a>
						</td>
						<td></td>
						{% endif %}
					</tr>
					{% endfor %}
				</tbody>
			</table>
		</div>
		<div class="col-12 col-sm-12 col-lg-6 text-center">
			<table class="table my_custom_table">
				<thread class="my_custom_thead">
					<tr>
						<th>
							Checkout
						</th>
					</tr>
				</thread>
				<tbody>
					<tr>
						<td>
							Please review your shopping cart item before proceeding with the order payment.
						</td>
					</tr>
					<tr>
						<td class="text-left">
							Your total is: <strong>${{total}}</strong>
						</td>
					</tr>
				</tbody>
			</table>
			<div class="mx-auto">
				<a href="{% url 'shop:all_product' %}" class="btn-secondary btn-block my_custom_button">Continue Shopping</a>
			</div>
		</div>
	</div>
	{% endif %}
{% endblock %}

models.py

from shop.models import Product

def add_cart(request, Product_id):
	product = Product.objects.get(id=product_id)
	try:
		cart = Cart.objects.get(cart_id=_cart_id(request))
	except Cart.DoesNotExist:
		cart = Cart.objects.create(
				cart_id = _cart_id(request)
			)
		cart.save()
	try:
		cart_item = CartItem.objects.get(product=product, cart=cart)
		cart_item.quantity += 1
		cart_item.save()
	except CartItem.DoesNotExist:
		cart_item = CartItem.objects.create(
				product = product,
				quantity = 1,
				cart = cart
			)
		cart_item.save()
	return redirect('cart:cart_detail')

urls.py

urlpatterns = [
	path('add/<int:product_id>/', views.add_cart, name='add_cart'),
	path('', views.cart_detail, name='cart_detail'),
]

product_detail.html

<a class="btn btn-secondary" href="{% url 'cart:add_cart' product.id %}">Add to Cart</a>

cart/views.py

def cart_remove(request, product_id):
	cart = Cart.objects.get(cart_id=_cart_id(request))
	product = get_object_or_404(Product, id=product_id)
	cart_item = CartItem.objects.get(product=product, cart=cart)
	if cart_item.quantity > 1:
		cart_item.quantity -= 1
		cart_item.save()
	else:
		cart_item.delete()
	return redirect('cart:cart_detail')

def full_remove(request, product_id):
	cart = Cart.objects.get(cart_id=_cart_id(request))
	product = get_object_or_404(Product, id=product_id)
	cart_item = CartItem.objects.get(product=product, cart=cart)
	cart_item.delete()
	return redirect('cart:cart_detail')

urls.py

app_name = 'cart'

urlpatterns = [
	path('add/<int:product_id>/', views.add_cart, name='add_cart'),
	path('', views.cart_detail, name='cart_detail'),
	path('remove/<int:product_id>/', views.cart_remove, name='cart_remove'),
	path('full_remove/<int:product_id>/', views.full_remove, name='full_remove')
]

cart/context_processors.py

from .models import Cart, CartItem
from .views import _cart_id

def counter(request):
	item_count = 0
	if 'admin' in request.path:
		return {}
	else:
		try:
			cart = Cart.objects.filter(cart_id=_cart_id(request))
			cart_items = CartItem.objects.all().filter(cart=cart[:1])
			for cart_item in cart_items:
				item_count += cart_item.quantity
		except Cart.DoesNotExist:
			item_count = 0
	return dict(item_count = item_count)

settings.py

            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'cart.context_processors.counter',
            ],

navbar.html

			{% if item_count > 0 %}
			<li class="nav-item">
				<a class="nav-link" href="{% url 'cart:cart_detail' %}">({{item_count}})</a>
			</li>
			{% endif %}

cart.html

						{% if cart_item.quantity < cart_item.product.stock %}
						<td>
							<a href="{% url 'cart:add_cart' cart_item.product.id %}" class="custom_a"><i class="fas fa-plus-circle custom_icon"></i></a>

							<a href="{% url 'cart:cart_remove' cart_item.product.id %}" class="custom_a"><i class="fas fa-minus-circle custom_icon"></a>

							<a href="{% url 'cart:full_remove' cart_item.product.id %}" class="custom_item"><i class="far fa-trash-alt"></a>
						</td>
						{% else %}
						<td>
							<a href="{% url 'cart:cart_remove' cart_item.product.id %}" class="custom_a"><i class="fas fa-minus-circle custom_icon"></a>

							<a href="{% url 'cart:full_remove' cart_item.product.id %}" class="custom_item"><i class="far fa-trash-alt"></i></a>
						</td>
						<td></td>
						{% endif %}

なるほど、ただこれだと、ログアウトした時の処理などが入ってないから、完成には遠いな。Libraryはないのかしら?

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

### search app作成
$ python3 manage.py startapp search

setting.py

INSTALLED_APPS = [
    'shop',
    'search',
    // 省略
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'shop', 'templates/'), os.path.join(BASE_DIR, 'search', 'templates/')],
        // 省略
    },
]

search/urls.py

from django.urls import path
from . import views

app_name = 'search'

urlpatterns = [
	path('', views.search_result, name='search_result'),
]

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('shop/', include('shop.urls')),
    path('search/', include('search.urls')),
]

search/views.py

from django.shortcuts import render
from shop.models import Product

def search_result(request):
	products = Product.objects.all()
	return render(request, 'search.html', {'products': products})

navbar.html

		<form class="form-inline my-2 my-lg-0" action="{% url 'search:search_result' %}" method="get">
			<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="q">
			<button class="btn btn-secondary my-2 my-sm-0" type="submit"><i class="fas fa-search"></i></button>
		</form>

search.html

{% extends "base.html" %}
{% load static %}

{% block metadescription %}
	 We have a variety of stunning and comfy cushions. Lock for the one that suits your needs.
{% endblock %}

{% block title %}
	Search - Perfect Cushion Store
{% endblock %}

{% block content %}
<div>
	<p class="text-center my_search_text">You have searched for: <b>"{{ query }}"</b></p>
</div>
<div class="container">
	<div class="row mx-auto">
		{% for product in products %}
		<div class="my_bottom_margin col-9 col-sm-12 com-md-4 com-md-12 col-lg-4">
			<div class="card text-center" style="min-width: 18rem;">
				<a href="{{product.get_url}}"><img class="card-img-top my_image" src="{{product.image.url}}" alt="{{product.name}}"></a>
				<div class="card-body">
					<h4>{{product.name}}</h4>
					<p>${{product.price}}</p>
				</div>
			</div>
		</div>
		{% empty %}
		<div class="row mx-auto">
			<p class="text-center my_search_text">0 results found.</p>
		</div>
		{% endfor %}
	</div>
</div>
{% endblock %}

OKでしょう。

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

一覧から画像をクリックすると遷移する商品詳細ページを作成します。

shop/models.py
L reverseとは、Djangoのurlsに設定された名前をパラメータとして渡すとURLを返す。

from django.urls import reverse

class Product(models.Model):
	// 省略

	def get_url(self):
		return reverse('shop:product_detail', args=[self.slug])

shop/urls.py

app_name = 'shop'

urlpatterns = [
	// 省略
	path('<slug:product_slug/>', views.product_detail, name='product_detail'),
]

shop/views.py

def product_detail(request, product_slug):
	try:
		product = Product.objects.get(slug=product_slug)
	except Exception as e:
		raise e
	return render(request, 'shop/product_detail.html', {'product': product})

shop/templates/shop/product_detail.html

{% extends "base.html" %}
{% load static %}

{% block metadescription %}
	{{ product.description|truncatewords:155}}
{% endblock %}

{% block title %}
		{{ product.name }} - Perfect Cushion Store
{% endblock %}

{% block content %}
<div>
	<div>
		<p><a href="{% url 'shop:all_product' %}">Home</a>|<a href="{{product.get_url}}">{{product.category}}</a></p>
	</div>
	<div>
		<br>
		<div>
			<div>
				<div>
					<img src="{{product.image.url}}" alt="{{product.name}}">
				</div>
			</div>
			<div>
				<div>
					<h1>{{product.name}}</h1>
					<p>${{product.price}}</p>
					<p>Product Description</p>
					<p>{{product.description}}</p>
					{% if product.stock <= 0 %}
					<p><b>Out of Stock</b></p>
					{% else %}
					<a href="">Add to Cart</a>
					{% endif %}
				</div>
			</div>
		</div>
	</div>
</div>
{% endblock %}

shop/templates/shop/product_list.html

			<div>
				<a href="{{product.get_url}}"><img src="{{ product.image.url }}" alt="{{product.name}}"></a>
				<div>
					<h4>{{product.name}}</h4>
					<p>${{product.price}}</p>
				</div>
			</div>

static/css/custom.css

.nav-item {
	letter-spacing: .2em;
	font-size: 14px;
	text-transform: uppercase;
}

.dropdown-item {
	font-size: 14px;
	letter-spacing: .2em;
	text-transform: uppercase;
}

/* google font */
body {
	font-family: 'Roboto', sans-serif;
}
.my_footer {
	background-color: #f8f9fa;
	height: 60px;
}

.my_footer p {
	padding-top: 20px;
	font-size: 14px;
}

base.html

	<link rel="stylesheet" href="{% static 'css/custom.css' %}">
	<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">

スタイリングをしていきます。

orange, bananaを追加します。

### ページネーション
views.py

from django.core.paginator import Paginator, EmptyPage, InvalidPage
def all_products(request):
	products = Product.valid_objects.all()

	paginator = Paginator(products_list, 3)
	try:
		page = int(request.GET.get('page','1'))
	except:
		page = 1

	try:
		products = paginator.page(page)
	except (EmptyPage, InvalidPage):
		products = paginator.page(paginator.num_pages)
		
	return render(request, 'shop/product_list.html',{'products':products})

product_list.html

<div class="row">
	<div class="mx-auto">
		{% if products.paginator.num_pages > 1%}
		<hr>
		<div class="text-center">
			{% for pg in products.paginator.page_range %}
			<a href="?page={{pg}}" class="btn btn-light btn-sm {% if products.number == pg %}active{% endif %}">{{pg}}</a>
			{% endfor %}
		</div>
		{% endif %}
	</div>
</div>

商品数が多い場合は使えないけど、こういう書き方があるんやな

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

テンプレートを作成していく

template/base.html
L テンプレートで変数使用時は{% block title %}{% endblock %} と書く
L includeは include ‘header.html’

{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="description" content="{% block metadescription %}{% endblock %}">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <title>{% block title %}{% endblock %}</title>
</head>
<body>
	<div>
		{% include 'header.html' %}
		{% include 'navbar.html' %}
		{% block content %}
		{% endblock %}
	</div>
		{% include 'footer.html' %}
		    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

template/header.html

{% load staticfiles %}
<header>
	<center>
		<img src="{% static 'img/logo.png' %}" alt="Perfect Cushion Store">
	</center>
</header>

template/navbar.html

<nav>
	<ul>
		<li><a href="{% url 'shop:all_product' %}">All Products</a></li>
		<li>Your Cart()</li>
	</ul>
</nav>

template/footer.html

<div>
	<p>© shoppingcart, with Django</p>
</div>

template/shop/product_list.html
L entends “base.html” でテンプレートを呼び出す

{% entends "base.html" %}
{% load staticfiles %}

{% block metadescription %}
	{% if category %}
{{ category.description|truncatewords:155}}
	{% else %}
		welecome to the cushion store where you can buy comfy and awesome cushions.
	{% endif %}
{% endblock %}

{% block title %}
	{% if category %}
{{ category.name }} - Perfect Cushion Store
	{% else %}
		See Our Cushion Collection - Perfect Cushion Store
	{% endif %}
{% endblock %}

{% block content %}
<div>
	<img src="{% static 'img/banner.jpg' %}" alt="Our Products Collection">
</div>
<br>
<div>
	<h1>Our Products Collection</h1>
	<p>Finding the perfect cushion for your room can add to the levels of comfort and sense of style throughout your home.</p>
</div>

<div>
	<div>
		{% for product in products %}
		<div>
			<div>
				<a href=""><img src="{{ product.image.url }}" alt="{{product.name}}"></a>
				<div>
					<h4>{{product.name}}</h4>
					<p>${{product.price}}</p>
				</div>
			</div>
		</div>
		{% endfor %}
	</div>
</div>
{% endblock %}

shop/admin.py

from django.contrib import admin
from .models import Friend, Category, Product

admin.site.register(Friend)

class CategoryAdmin(admin.ModelAdmin):
	list_display = ['name', 'slug']
	prepopulated_field = {'slug':('name',)}
admin.site.register(Category, CategoryAdmin)

class ProductAdmin(admin.ModelAdmin):
	list_display = ['name','price', 'stock', 'available', 'created', 'updated']
	list_editable = ['price', 'stock', 'available']
	prepopulated_field = {'slug':('name',)}
	list_per_page = 20
admin.site.register(Product, ProductAdmin)

settings.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
    )
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')

urls.py

from django.contrib import admin
from django.urls import path, include
import shop.views as shop

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('shop/', include('shop.urls')),
]

if settings.DEBUG:
	urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
	urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

static/img に、apple.jpeg, banner.jpeg, logo.jpeg を入れます。
admin画面からデータを入力して、確認します。
http://192.168.33.10:8000/shop/all

おおお、なんか感動した。乾いた感動だけど。

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)

typescript入門

$ npm –version
$ npm init
$ sudo npm install typescript
$ echo export PATH=\$PATH:`pwd`/node_modules/.bin >> ~/.bashrc
$ source ~/.bashrc
$ tsc –version
Version 4.2.4

function hello(name: string): void {
	console.log("Hello " + name + "!");
}
let your_name: string = "Yamada";
hello(your_name);

$ tsc sample.ts
$ node sample.js
Hello Yamada!

WordPressでPluginをゼロから作りたい

Pluginのフォルダにファイルを作成し、ライセンス情報を記載する

/*
	Plugin Name: CustomIndexBanner
	Plugin URI: http://hpscript.com/blog/
	Description: indexページに表示可能なバナーの設定
	Version: 1.0.0
	Author: Hpscript
	Author URI: http://hpscript.com/blog/
	License: MIt
*/

すると、プラグインとして自動で認識される

メニュー追加

add_action('init', 'CustomIndexBanner::init');

class CustomIndexBanner {

	static function init(){
		return new self();
	}

	function __construct(){
		if(is_admin() && is_user_logged_in()){
			add_action('admin_menu', [$this, 'set_plugin_menu']);
			add_action('admin_menu', [$this, 'set_plugin_sub_menu']);
		}
	}

	function set_plugin_menu(){
		add_menu_page (
			'カスタムバナー', // ページタイトル
			'カスタムバナー', // メニュータイトル
			'manage_options', // 権限
			'custom-index-banner', // ページを開いたときのURL
			[$this, 'show_about_plugin'], // メニューに紐づく画面を描画するcallback関数
			'dashicons-format-gallery', // アイコン
			99 // 表示位置オフセット
		);
	}
	function set_plugin_sub_menu(){
		add_submenu_page(
			'custom-index-banner',
			'設定',
			'設定',
			'manage_options',
			'custom-index-banner-config',
			[$this, 'show_config_form']
		);
	}
}

	function show_about_plugin(){
		$html = "<h1>カスタムバナー</h1>";
		$html .= "<p>トップページに表示するバナーを指定できます</p>";

		echo $html;
	}

	function show_config_form(){

?>
	<h1>カスタムバナーの設定</h1>
<?php
	}
}

### フォームの作成

	const VERSION = '1.0.0';
	const PLUGIN_ID = 'custom-index-banner';
	const CREDENTIAL_ACTION = self::PLUGIN_ID . '-nonce-action';
	const CREDENTIAL_NAME = self::PLUGIN_ID . '-nonce-key';
	const PLUGIN_DB_PREFIX = self::PLUGIN_ID . '_';


	function show_config_form(){
		// wp_optionsを引っ張る
		$title = get_option(self::PLUGIN_DB_PREFIX . "_title");
?>
	<div class="wrap">
		<h1>カスタムバナーの設定</h1>

		<form action="" method='post' id="my-submenu-form">
			<?php wp_nonce_field(self::CREDENTIAL_ACTION, self::CREDENTIAL_NAME) ?>

			<p>
				<label for="title">タイトル:</label>
				<input type="text" name="title" value="<?= $title ?>"/>
			</p>

			<p><input type="submit" value="保存" class="button button-primary button-large"></p>
		</form>
	</div>
<?php
	}
}


	const CONFIG_MENU_SLIG = self::PLUGIN_ID . '-config';
	function save_config(){

		if(isset($_POST[self::CREDENTIAL_NAME]) && $_POST[self::CREDENTIAL_NAME]){
			if(check_admin_referer(self::CREDENTIAL_ACTION, self::CREDENTIAL_NAME)){

				$key =
				$title = $_POST($value['title']) ? $_POST['title'] : "";

				update_option(self::PLUGIN_DB_PREFIX . $key, $title);
				$completed_text = "設定の保存が完了しました。管理画面にログインした状態で、トップページにアクセスし変更が正しく反映されたか確認してください。";

				set_transient(self::COMPLETE_CONFIG, $completed_text, 5);

				wp_safe_redirect(menu_page_url(self::CONFIG_MENU_SLUG), false);

			}
		}
	}

なんやこれは。。。 プラグインの実装はテーマエディタではなく、プラグインのソースコードでカスタマイズすんのか。 時間かかるな。