Django

Django-Extensions #

pip install -U django-extensions ipython
# add 'django_extensions' to INSTALLED_APPS
python manage.py shell_plus --ipython
python manage.py shell_plus --ptpython

# 默认shell优先顺序是: ptpython, bpython, ipython, python
# settings.py 指定
# SHELL_PLUS = 'ipython'

文本直接作HTML #

# safe filter
{{ my_html_content | safe }}

# autoescape tag
{% autoescape off %}
  {{ my_html_content }}
{% endautoescape %}

template 中的字典访问,需要用到

custome template filter #

Django migrate SQLite to Postgres #

  • dump SQLite schema and data to a file
python manage.py dumpdata > datadump.json

change settings.py to Postgres backend #

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'ct_dev',
        'USER': 'ct',
        'PASSWORD': 'ct',
        'HOST': '127.0.0.1',
        'PORT': '5432'
    }
}

创建所有的表 python manage.py migrate --run-syncdb #

exclude contenttype data (needed for the following loaddata) #

python manage.py shell
from django.contrib.contenttypes.models import ContentType
ContentType.objects.all().delete()
quit()

python manage.py loaddata datadump.json #

python manage.py collectstatic #

Django 中可能有多个 APP, 这个命令就是把他们的静态文件复制到 STATIC_ROOT,方便 nginx 等的 serve。

MD5 hash suffix #

It’s not part of the default behavior of collectstatic, as settings.STATICFILES_STORAGE defaults to StaticFilesStorage (which doesn’t do that).

https://docs.djangoproject.com/en/4.2/ref/contrib/staticfiles/#manifeststaticfilesstorage

TL;DR 目的是为了防止cache

python manage.py compress #

Django compressor

Compresses linked and inline JavaScript or CSS into a single cached file.

一般是发生在 python manage.py collectstatic 之后

一个使用参考 https://cheat.readthedocs.io/en/latest/django/compressor.html