Skip to content

Instantly share code, notes, and snippets.

@x-yuri
Created September 12, 2017 18:03
Show Gist options
  • Save x-yuri/d379364f249e69a73ec51bd82751cd76 to your computer and use it in GitHub Desktop.
Save x-yuri/d379364f249e69a73ec51bd82751cd76 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
set -eu
# USAGE: ./create-django-app-with-image-field.sh django-app-1
# NOTE. it does rm -rf django-app-1
NAME=$1
# DJANGO_VER=1.11
DJANGO_VER=1.7
PATH_TO_REPO=/path/to/imagekit/repository
ignore_errors() {
set +eu
"$@"
set -eu
}
rm -rf "$NAME"
if [ "$DJANGO_VER" = 1.7 ]; then
python3.4 -m venv "$NAME"
else
python -m venv "$NAME"
fi
cd "$NAME"
ignore_errors . bin/activate
pip install django==$DJANGO_VER pillow file://$PATH_TO_REPO
django-admin startproject "$NAME"
cd "$NAME"
./manage.py startapp a1
git init
git add *
git commit -m 'Initial commit'
mkdir -p a1/templates/a1
echo '<img src="{{ img.f1_thumb.url }}">' \
> a1/templates/a1/index.html
echo 'from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
class Model1(models.Model):
f1 = models.ImageField()
f1_thumb = ImageSpecField(source="f1",
processors=[ResizeToFill(50, 50)])' \
>> a1/models.py
echo 'from .models import Model1
def t1(request):
return render(request, "a1/index.html", {
"img": Model1.objects.first()
})' \
>> a1/views.py
if [ "$DJANGO_VER" = 1.7 ]; then
echo 'INSTALLED_APPS += ("imagekit",)
INSTALLED_APPS += ("a1",)' \
>> "$NAME/settings.py"
else
echo 'INSTALLED_APPS += ["imagekit"]
INSTALLED_APPS += ["a1"]' \
>> "$NAME/settings.py"
fi
echo 'MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"' \
>> "$NAME/settings.py"
echo 'from django.conf import settings
from django.conf.urls.static import static
import a1.views
urlpatterns += [url(r"^t1$", a1.views.t1)]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)' \
>> "$NAME/urls.py"
./manage.py makemigrations
./manage.py migrate
curl -sSLo 1.png http://placehold.it/100x100
echo '#!/usr/bin/env python
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "'"$NAME"'.settings")
import django
django.setup()
from a1.models import Model1
from django.core.files.images import ImageFile
Model1.objects.all().delete()
m = Model1.objects.create()
m.f1 = ImageFile(open("1.png", "rb"))
m.save()' \
> init.py
chmod u+x init.py
./init.py
# ./manage.py runserver 8001
find media -type f -exec file {} \;
./manage.py generateimages imagekit:thumbnail \
| sed -E 's/^/ > /'
find media -type f -exec file {} \;
./manage.py generateimages a1:model1:f1_thumb \
| sed -E 's/^/ > /'
find media -type f -exec file {} \;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment