【django】社内SNSアプリを作ってみる⑤(imageファイルの取り扱い等)【pythonメモ】

pythonLOGO
記事内にプロモーションを含むことがあります

当サイトの記事内では、アフィリエイト広告を掲載している場合があります。

imageファイルの取り扱い

http://127.0.0.1:8000/admin/

adminに入って「add」ボタンから

http://127.0.0.1:8000/admin/boardapp/boardmodel/add/

適当な画像をアップしてみる

一見、正常に保存されているように見えるが

imageのfoodfighter_ramen.pngを選ぼうとすると

そういうの無いけど消しちゃった?って聞かれる。

 →画像が保存されていない

ので、その設定をやっていく。

models.py

from django.db import models

# Create your models here.

class BoardModel(models.Model):
  title = models.CharField(max_length=100)
  content = models.TextField()
  author = models.CharField(max_length=100)
  images = models.ImageField(upload_to='') #←ここに格納方法が無い
  good = models.IntegerField()
  read = models.IntegerField()
  readtext = models.CharField(max_length=200)

settings.py

"""
Django settings for boardproject project.

Generated by 'django-admin startproject' using Django 3.0.8.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'k&tz9=)tob9a8f(_oh492q1817)*pz8lk4dw7e*-hkw15*&vwg'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

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

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'boardproject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR, 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'boardproject.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # 追加

MEDIA_URL = '/medi/' # 追加

再度、http://127.0.0.1:8000/admin/boardapp/boardmodel/add/を確認する

http://127.0.0.1:8000/admin/boardapp/boardmodel/

正常のアップロードできたようです。

http://127.0.0.1:8000/admin/boardapp/boardmodel/2/change/

もう一度ファイルを触ろうとすると

エラー・・・でもこれで合っています。

なぜならdjangoでは、一個一個の画像とurlがリンクしていて画像が入っているurlを指定することでその画像を呼び出す操作が必要になる。

ただし、実務上では、pythonのコードで画像をごちゃごちゃする必要は無く、Webサーバー上、またはcssでいじれる部分なので、そういった事はしない。

これからする事は、あくまで開発環境の中だけでやる事と思っていた方が良い。

ところで、さっきアップした画像はここに格納されている。

つまり関連付けができていない。

調べてみる。(結果)

https://docs.djangoproject.com/ja/3.0/howto/static-files/

boardproject>urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('boardapp.urls')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

で、ファイルを選んでやると

http://127.0.0.1:8000/admin/boardapp/boardmodel/2/change/
http://127.0.0.1:8000/medi/tube_syouga.png

正常に表示されました。

cssの設定

signupページにCSSを適用していく

http://127.0.0.1:8000/signup/

どこに適用させていくかというと、templates > base.html の部分

まずはsignup.htmlに

{% extends 'base.html' %}

{% block customecss %}  <!ー追記->

{% endblock customecss %} <!ー追記->

{% block content %}
  <form class="form-signin" method="POST" action=''>{% csrf_token %}
    <img class="mb-4" src="/docs/4.5/assets/brand/bootstrap-solid.svg" alt="" width="72" height="72">
    <h1 class="h3 mb-3 font-weight-normal">Please sign up</h1>

    {% if error %}
    {{ error }}
    {% endif %}

    <label for="inputEmail" class="sr-only">Email address</label>
    <input type="text" id="inputEmail" class="form-control" name='username' placeholder="username" required autofocus>
    <label for="inputPassword" class="sr-only">Password</label>
    <input type="password" id="inputPassword" class="form-control" name='password' placeholder="Password" required>
    <div class="checkbox mb-3">
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    <p class="mt-5 mb-3 text-muted">© 2017-2020</p>
  </form>
{% endblock content %}

を入れ込んで、imageファイルを入れ込んだようにsettings.pyに追記をする

settings.py

"""
Django settings for boardproject project.

Generated by 'django-admin startproject' using Django 3.0.8.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'k&tz9=)tob9a8f(_oh492q1817)*pz8lk4dw7e*-hkw15*&vwg'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

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

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'boardproject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR, 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'boardproject.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static') #追記
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/medi/'

追記部分にstaticを定義したので、staticフォルダをmanage.pyがある階層に設置する

こんな感じ、このフォルダを作った上でurlのつなぎこみが必要になるので

urls.py

ここを参考

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('boardapp.urls')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

ここでcssをstatic内に仕込んでいく

static > style.css

適用させるのは、

https://getbootstrap.com/docs/4.5/examples/sign-in/

こんな感じ。

ソースコードを開いて

ここのsignin.cssを参考に

こいつをコピペする

html,
body {
  height: 100%;
}

body {
  display: -ms-flexbox;
  display: flex;
  -ms-flex-align: center;
  align-items: center;
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: #f5f5f5;
}

.form-signin {
  width: 100%;
  max-width: 330px;
  padding: 15px;
  margin: auto;
}
.form-signin .checkbox {
  font-weight: 400;
}
.form-signin .form-control {
  position: relative;
  box-sizing: border-box;
  height: auto;
  padding: 10px;
  font-size: 16px;
}
.form-signin .form-control:focus {
  z-index: 2;
}
.form-signin input[type="email"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}
.form-signin input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}

その他のhtmlにcssを反映させていく

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

{% block customcss %} 
<link rel='stylesheet' type='text/css' href="{% static 'style.css' %}">
{% endblock customcss %} 

{% block content %}
  <form class="form-signin" method="POST" action=''>{% csrf_token %}
    <img class="mb-4" src="/docs/4.5/assets/brand/bootstrap-solid.svg" alt="" width="72" height="72">
    <h1 class="h3 mb-3 font-weight-normal">Please sign up</h1>

    {% if error %}
    {{ error }}
    {% endif %}

    <label for="inputEmail" class="sr-only">Email address</label>
    <input type="text" id="inputEmail" class="form-control" name='username' placeholder="username" required autofocus>
    <label for="inputPassword" class="sr-only">Password</label>
    <input type="password" id="inputPassword" class="form-control" name='password' placeholder="Password" required>
    <div class="checkbox mb-3">
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    <p class="mt-5 mb-3 text-muted">© 2017-2020</p>
  </form>
{% endblock content %}

そしてF5でリロードすると

http://127.0.0.1:8000/signup/

こうなる。長くなったので次回。



 
記事内にプロモーションを含むことがあります

当サイトの記事内では、アフィリエイト広告を掲載している場合があります。

あ、宜しければ・・・。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です