読者です 読者をやめる 読者になる 読者になる

Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

Angular4 + Django1.11 vol.12

参考サイト

https://www.codingforentrepreneurs.com/projects/angular-django/

Fix Broken Images

Image Field & Uploading Images

class Video(models.Model):
    name            = models.CharField(max_length=220)
    slug            = models.SlugField(unique=True, blank=True)
    embed           = models.CharField(max_length=120, help_text='Youtube Embed Code', null=True, blank=True)
    # image_path      = models.CharField(max_length=120,blank=True, null=True, default='https://madangler.s3.amazonaws.com/static/ang/assets/images/nature/4.jpg')
    image_path      = models.ImageField(upload_to='images/', null=True, blank=True)
    active          = models.BooleanField(default=True)
    featured        = models.BooleanField(default=False)
    timestamp       = models.DateTimeField(auto_now_add=True)
  • $ pip install pillow する。

  • videso/serializers.py のimage_pathの箇所を修正する。

from rest_framework import serializers

from videos.models import Video

class VideoSerializer(serializers.ModelSerializer):
    image = serializers.SerializerMethodField()
    class Meta:
        model = Video
        fields = ['name', 'slug', 'embed', 'featured', 'image']

    # obj.imageがある場合は、image.urlの文字列を返す(無い場合は、デフォルトの値を返す)
    def get_image(self,obj):
        if obj.image:
            return str(obj.image.url)
        return "/static/ang/assets/images/nature/1.jpg"


class VideoDetailSerializer(serializers.ModelSerializer):
    image       = serializers.SerializerMethodField()
    is_promo    = serializers.SerializerMethodField()
    class Meta:
        model = Video
        fields = [
            'name',
            'slug',
            'embed',
            'featured',
            'image',
            'is_promo'
            ]

    # obj.imageがある場合は、image.urlの文字列を返す(無い場合は、デフォルトの値を返す)
    def get_image(self,obj):
        if obj.image:
            return str(obj.image.url)
        return "/static/ang/assets/images/nature/1.jpg"

    def get_is_promo(self,obj):
        return False
  • さらに、デフォルトのreturnを、相対パスにする。
from django.contrib.staticfiles.templatetags.staticfiles import static
...

class VideoSerializer(serializers.ModelSerializer):
...

    def get_image(self,obj):
        if obj.image2:
            return str(obj.image2.url)
        return static("ang/assets/images/nature/1.jpg")


class VideoDetailSerializer(serializers.ModelSerializer):
...
    def get_image(self,obj):
        if obj.image2:
            return str(obj.image2.url)
        return static("ang/assets/images/nature/1.jpg")

    def get_is_promo(self,obj):
        return False

Env Config Variables

import datetime
import os
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
if AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY:
    AWS_FILE_EXPIRE = 200
    AWS_PRELOAD_METADATA = True
    AWS_QUERYSTRING_AUTH = True

    DEFAULT_FILE_STORAGE = 'tryangular.aws.utils.MediaRootS3BotoStorage'
    STATICFILES_STORAGE = 'tryangular.aws.utils.StaticRootS3BotoStorage'
    AWS_STORAGE_BUCKET_NAME = 'tryangular'
    S3DIRECT_REGION = 'us-west-2'
    S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME
    MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME
    MEDIA_ROOT = MEDIA_URL
    STATIC_URL = S3_URL + 'static/'
    ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'

    two_months = datetime.timedelta(days=61)
    date_two_months_later = datetime.date.today() + two_months
    expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT")

    AWS_HEADERS = {
     'Expires': expires,
     'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), ),
    }
  • localで、 .envファイルを作りたい場合は、以下のようにコマンドをうつと.envファイルを作成できる。
$ heroku config:get CONFIG-VAR-NAME -s >> .env
$ heroku config:get AWS_ACCESS_KEY_ID -s >> .env
$ heroku config:get AWS_SECRET_ACCESS_KEY -s >> .env

Secure your Site with Free SSL / TLS