Djangoroidの奮闘記

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

Angular4 + Django1.11 vol.3

参考サイト

https://www.codingforentrepreneurs.com/projects/angular-django/ https://www.codingforentrepreneurs.com/blog/random-string-generator-in-python/ https://www.codingforentrepreneurs.com/blog/a-unique-slug-generator-for-django/

Videos Django App

  • ng buildを起動した状態にしておく。
ng build --prod --output-path /Users/yassy/Desktop/djangular4/backend/src/static/ang/ --watch --output-hashing none
  • deploy.shに上記のコマンドを記載しておく。

  • 現在の仕様では、video.service.tsが、videos.jsonからデータを取得しているが、これをdjangoのデータベースから直接持ってくるように設定したい。

  • まず、videos appを作成する。$ python manage.py startapp videos

  • videos の modelを作成する。

from django.db import models

# Create your models here.

class Video(models.Model):
    name = models.CharField(max_length=220)
    slug = models.SlugField(unique=True, blank=True)
    embed = models.CharField(max_length=120, null=True, blank=True)
    featured = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

'''
     "name": "Welcome",
     "slug": "item-1",
     "embed": "1hyjLD7pk10",
     "image": "/static/ang/assets/images/nature/4.jpg",
     "featured": true
    },
'''

Auto Generate Slug

import random
import string
from django.utils.text import slugify


def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

'''
random_string_generator is located here:
http://joincfe.com/blog/random-string-generator-in-python/
'''

def unique_slug_generator(instance, new_slug=None):
    if new_slug is not None:
        slug = new_slug
    else:
        slug = slugify(instance.title)

    Klass = instance.__class__
    qs_exists = Klass.objects.filter(slug=slug).exists()
    if qs_exists:
        new_slug = "{slug}-{randstr}".format(
                    slug=slug,
                    randstr=random_string_generator(size=4)
                )
        return unique_slug_generator(instance, new_slug=new_slug)
    return slug
    ```

* 最終的にvideos/modelssは以下のように修正

from django.db import models from django.db.models.signals import pre_save

Create your models here.

from .utils import unique_slug_generator

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) featured = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return self.name

def title(self):
    return self.name

def video_pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance)

pre_save.connect(video_pre_save_receiver, sender=Video)