73 lines
1.9 KiB
Python
73 lines
1.9 KiB
Python
import os
|
|
from datetime import datetime
|
|
|
|
from django.utils import timezone
|
|
from django.utils.text import slugify
|
|
|
|
|
|
def common_user_str(user):
|
|
if not user:
|
|
return ""
|
|
return user.full_name if user.full_name else user.mobile
|
|
|
|
|
|
def common_datetime_str(datetime):
|
|
if not datetime:
|
|
return ""
|
|
try:
|
|
if timezone.is_aware(datetime):
|
|
datetime = timezone.localtime(datetime)
|
|
else:
|
|
datetime = timezone.make_aware(datetime, timezone.get_current_timezone())
|
|
except Exception:
|
|
pass
|
|
return datetime.strftime("%Y.%m.%d %H:%M")
|
|
|
|
|
|
def common_date_str(datetime):
|
|
if not datetime:
|
|
return ""
|
|
try:
|
|
if timezone.is_aware(datetime):
|
|
datetime = timezone.localtime(datetime)
|
|
else:
|
|
datetime = timezone.make_aware(datetime, timezone.get_current_timezone())
|
|
except Exception:
|
|
pass
|
|
return datetime.strftime("%Y.%m.%d")
|
|
|
|
|
|
def file_name_datetime_str():
|
|
dt = timezone.now()
|
|
return f"{dt.year}-{dt.month}-{dt.day}-{dt.hour}-{dt.minute}-{dt.second}"
|
|
|
|
|
|
def upload_to_by_date(instance, filename):
|
|
today = datetime.now()
|
|
timestamp = today.strftime("%Y%m%d%H%M%S")
|
|
file_extension = os.path.splitext(filename)[1]
|
|
new_filename = f"{timestamp}{file_extension}"
|
|
return os.path.join(f"storage/{today.year}/", new_filename)
|
|
|
|
|
|
def calculate_age(birth_date):
|
|
"""
|
|
Helper Function to calculate age from birth date
|
|
"""
|
|
if not birth_date:
|
|
return None
|
|
|
|
today = timezone.localdate()
|
|
age = today.year - birth_date.year - int((today.month, today.day) < (birth_date.month, birth_date.day))
|
|
return age
|
|
|
|
|
|
def generate_slug(title, Object, pk):
|
|
base_slug = slugify(title, allow_unicode=True)
|
|
slug = base_slug
|
|
counter = 2
|
|
while slug and Object.objects.filter(slug=slug).exclude(pk=pk).exists():
|
|
slug = f"{base_slug}-{counter}"
|
|
counter += 1
|
|
return slug
|