#!/usr/bin/env python # -*- coding: utf-8 -*- ''' (Data)models which describe the structure of data to be saved into database. ''' import os import uuid from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.translation import ugettext_lazy as _ from lostplaces.models.abstract_models import Expireable from lostplaces.models.place import Place from easy_thumbnails.fields import ThumbnailerImageField from easy_thumbnails.files import get_thumbnailer def generate_profile_image_filename(instance, filename): """ Callback for generating filename for uploaded explorer profile images. Returns filename as: explorer_pk-username.jpg """ return 'explorers/' + str(instance.user.pk) + '-' + str(instance.user.username) + '.' + filename.split('.')[-1] class Explorer(models.Model): """ Profile that is linked to the a User. Every user has a profile. """ user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='explorer' ) profile_image = ThumbnailerImageField( blank=True, null=True, upload_to=generate_profile_image_filename, resize_source=dict(size=(400, 400), sharpen=True), verbose_name=_('Profile image'), help_text=_('Optional profile pic for display in explorer profile') ) favorite_places = models.ManyToManyField( Place, related_name='favorite_places', verbose_name='Explorers favorite places', blank=True ) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Explorer.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.explorer.save() class Voucher(Expireable): """ Vouchers are authorization tokens to allow the registration of new users. A voucher has a code, a creation and a deletion date, which are all positional. Creation date is being set automatically during voucher creation. created_when = models.DateTimeField(auto_now_add=True) expires_when = models.DateTimeField() """ code = models.CharField(unique=True, max_length=30) @property def valid(self): return not self.is_expired def __str__(self): return "Voucher " + str(self.code)