USE_X_FORWARDED_HOST == True
X-Forwarded-Host
Django==1.3
South==0.7.3
pip install python-dateutil
>>> from datetime import datetime, timedelta
>>> from dateutil import relativedelta
>>> d1 = datetime.now()
>>> d2 = d1 + timedelta(days=285, hours=14, minutes=32, seconds=19)
>>> r = relativedelta.relativedelta(d2, d1)
>>> r.years, r.months, r.days, r.hours, r.minutes, r.seconds
(0, 9, 10, 14, 32, 19)
>>> from datetime import datetime, timedelta
>>> from dateutil import relativedelta
>>> r = relativedelta.relativedelta(datetime(2019, 12, 25), datetime.now())
>>> f'{r.months} мес {r.days} дн {r.hours:02}:{r.minutes:02}:{r.seconds:02}'
'9 мес 10 дн 04:32:01'
#!/bin/sh
set -o errexit
set -o pipefail
set -o nounset
if [ $DJANGO_DEBUG == "on" ]; then
./manage.py runserver 0.0.0.0:8000
elif [ $DJANGO_MODE == "worker" ]; then
./manage.py runworker
else
daphne -b 0.0.0.0 -p 8000 config.asgi:application
fi
#!/usr/bin/env python3
import ast
filename = 'file.txt'
# open file
with open(filename) as f:
# read lines one by one
for line in f:
# remove semicolon and new line characters from the end of the line
line = line.rstrip('\n;')
# parse string
data = ast.literal_eval(line)
# print representation of the data
print(repr(data))
import os
from django.db import models
class Article(models.Model):
title = models.CharField(
max_length=200,
)
image = models.ImageField(
blank=True,
upload_to='images',
)
@property
def thumbnail(self):
if self.image:
path, filename = os.path.split(self.image.url)
name, ext = os.path.splitext(filename)
filename = 'prefix_' + name + '_suffix' + ext
return os.path.join(path, filename)
import os
from django.contrib import admin
from django.utils.html import format_html
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = (
'title',
'get_thumbnail',
)
fields = (
'title',
'get_thumbnail',
)
readonly_fields = (
'get_thumbnail',
)
def get_thumbnail(self, obj):
if obj.image:
path, filename = os.path.split(self.image.url)
name, ext = os.path.splitext(filename)
filename = 'prefix_' + name + '_suffix' + ext
return format_html('<img src="{}">', os.path.join(path, filename))
get_thumbnail.short_description = 'Thumbnail'
get_logo.admin_order_field = 'image'
import os
from django.contrib import admin
from django.utils.html import format_html
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = (
'title',
'get_thumbnail',
)
fields = (
'title',
'get_thumbnail',
)
readonly_fields = (
'get_thumbnail',
)
def get_thumbnail(self, obj):
url = obj.thumbnail
return format_html('<img src="{}">', url) if url else ''
get_thumbnail.short_description = 'Thumbnail'
get_logo.admin_order_field = 'image'
import itertools
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue=fillvalue)
...
limit = 250
for index, items in enumerate(grouper(rows, limit)):
items = (i for i in items if i) # remove empty rows added by grouper
products = []
for item in items:
product = Product(
price=item[0],
shipping=item[1],
)
products.append(product)
Product.objects.bulk_create(products)
from django.db import transaction
...
limit = 250
for index, items in enumerate(grouper(rows, limit)):
with transaction.atomic():
for item in (i for i in items if i):
product = Product.objects.create(
price=item[0],
shipping=item[1],
)
# product can be used there to create another objects, e.g.:
for color in item[2].split(','):
ProductColor.objects.create(
product=product,
color=color,
)
import hashlib
import os
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.db import models
def upload_to(instance, filename, fieldname):
ext = os.path.splitext(filename)[1].lower()
class_name = instance.__class__.__name__.lower()
h = hashlib.sha256()
field = getattr(instance, fieldname)
for chunk in field.chunks():
h.update(chunk)
name = h.hexdigest()
return os.path.join(
class_name,
name + ext,
)
class OverwriteStorage(FileSystemStorage):
def get_available_name(self, name, max_length=None):
if self.exists(name):
os.remove(os.path.join(settings.MEDIA_ROOT, name))
return name
class Article(models.Model):
image = models.ImageField(
storage=OverwriteStorage(),
upload_to=lambda inst, fn: upload_to(inst, fn, 'image'),
)
pip install django-hashedfilenamestorage
DEFAULT_FILE_STORAGE = 'django_hashedfilenamestorage.storage.HashedFilenameFileSystemStorage'
from django.db import models
from django.db.models import Max, Sum
from django.utils.translation import ugettext_lazy as _
class Product(models.Model):
name = models.CharField(
_('Name'),
max_length=200,
db_index=True,
)
def __str__(self):
return self.name
class Document(models.Model):
INVOICE = 'I'
WAYBILL = 'W'
TYPE_CHOICES = (
(INVOICE, _('Invoice')),
(WAYBILL, _('Waybill')),
)
type = models.CharField(
_('Type'),
max_length=1,
choices=TYPE_CHOICES,
)
number = models.CharField(
_('Number'),
blank=True,
max_length=50,
)
created_at = models.DateTimeField(
_('Created'),
auto_now_add=True,
db_index=True,
)
@property
def total(self):
return self.items.aggregate(sum=Sum('total'))['sum']
class Meta:
ordering = ['-created_at']
class DocumentItem(models.Model):
document = models.ForeignKey(
Document,
models.CASCADE,
related_name='items',
)
position = models.PositiveIntegerField(
verbose_name=_('Position'),
editable=False,
db_index=True,
)
product = models.ForeignKey(
Product,
models.PROTECT,
)
price = models.DecimalField(
_('Price'),
max_digits=12,
decimal_places=2,
)
quantity = models.DecimalField(
_('Quantity'),
max_digits=10,
decimal_places=3,
)
total = models.DecimalField(
_('Total'),
max_digits=12,
decimal_places=2,
)
def save(self, *args, **kwargs):
if not self.position:
position = self.document.items.aggregate(Max('position'))['position__max'] or 0
self.position = position + 1
super(DocumentItem, self).save(*args, **kwargs)
from django.contrib import admin
from .models import Product, Document, DocumentItem
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
pass
class DocumentItemInline(admin.TabularInline):
model = DocumentItem
fields = (
'position',
'product',
'price',
'quantity',
'total',
)
readonly_fields = (
'position',
)
ordering = ['position']
@admin.register(Document)
class DocumentAdmin(admin.ModelAdmin):
inlines = [
DocumentItemInline,
]
list_display = (
'type',
'number',
'created_at',
'total',
)
list_filter = (
'type',
)
search_fields = (
'=number',
)
...
ingridients = models.ManyToManyField(
Food,
through='Ingredients',
through_fields=('recipe', 'food')
)
...
import operator
import functools
from django.db.models import Q
from .models import Item
def get_items(letters=''):
items = Item.objects.filter(active=True)
items = items.exclude(id__lt=100).exclude(id__gt=200)
if letters:
q = functools.reduce(operator.or_, (Q(name__istartswith=l) for l in letters))
items = items.filter(q)
return items
get_items('abc')
from django.db.models import Q
from .models import Item
def get_items(letters='', active=None):
q = Q()
if len(letters) == 3 and letters[1] == '-':
letters = (unichr(c) for c in range(ord(letters[0]), ord(letters[2]) + 1))
for letter in letters:
q |= Q(name__istartswith=letter)
if active is not None:
q &= Q(active=active)
return Item.objects.filter(q)
get_items(u'абвгд')
get_items(u'в-д')
get_items(u'а-я', True)
MYSITE_URL = '<abs_path>/domains/mysite.ru'
STATIC_ROOT = os.path.join(MYSITE_URL, 'static')
MEDIA_ROOT = os.path.join(MYSITE_URL, 'media')
python manage.py collectstatic
), a media выносить на отдельный домен (для предотвращения XSS уязвимостей).