Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- # python import
- import os
- import shutil
- from PIL import Image
- import random
- import re
- import mimetypes
- from io import StringIO
- # django import
- from django.db import models
- from django.db.models.signals import post_save
- from django.conf import settings
- from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
- from django.core.mail import send_mail
- from django.core.files import File
- from django.template.loader import render_to_string
- from django.utils import timezone
- from django.utils.crypto import get_random_string
- from django.core.files.uploadedfile import SimpleUploadedFile
- class UserManager(BaseUserManager):
- # 일반 유저 생성
- def create_user(self, email, password=None):
- # 이메일이 없는 경우 에러 호출
- if not email:
- raise ValueError("이메일은 필수 항목입니다.")
- user = self.model(
- email=self.normalize_email(email)
- )
- user.set_password(password)
- user.save()
- return user
- # 관리자 계정 생성
- def create_superuser(self, email, password=None):
- user = self.create_user(
- email,
- password=password
- )
- user.is_active = True
- user.is_admin = True
- user.save(using=self._db)
- return user
- def user_profile_location(instance, filename):
- return "users/%s/%s" % (instance, filename)
- class User(AbstractBaseUser):
- email = models.EmailField(max_length=255, unique=True)
- name = models.CharField(max_length=20, null=True, blank=True)
- phone = models.CharField(max_length=20, null=True, blank=True)
- image = models.ImageField(
- null=True,
- blank=True,
- upload_to=user_profile_location
- )
- is_active = models.BooleanField(default=False)
- is_admin = models.BooleanField(default=False)
- objects = UserManager()
- USERNAME_FIELD = 'email'
- def __str__(self):
- return str(self.email)
- def get_short_name(self):
- if self.name:
- return self.name
- return self.email.split('@')[0]
- @property
- def is_staff(self):
- return self.is_admin
- @property
- def get_user_profile_image(self):
- if self.image:
- return '/media/%s' % (self.image)
- return "/public/img/no_profile_1.png"
- @property
- def get_user_micro_thumb(self):
- micro = Thumbnail.objects.filter(user=self, type='micro')
- if micro.exists():
- return '/media/%s' % (micro[0].image)
- return self.get_user_profile_image
- @property
- def get_user_hd_thumb(self):
- hd = Thumbnail.objects.filter(user=self, type='hd')
- if hd.exists():
- return '/media/%s' % (hd[0].image)
- return self.get_user_profile_image
- def has_perm(self, perm, obj=None):
- return True
- def has_module_perms(self, app_label):
- return True
- def thumbnail_location(instance, filename):
- return "users/%s/thumb/%s" % (instance.user, filename)
- THUMB_CHOICES = (
- ("hd", "HD"),
- ("sd", "SD"),
- ("micro", "Micro"),
- )
- class Thumbnail(models.Model):
- user = models.ForeignKey(User)
- type = models.CharField(max_length=20, choices=THUMB_CHOICES, default='hd')
- height = models.CharField(max_length=20, null=True, blank=True)
- width = models.CharField(max_length=20, null=True, blank=True)
- image = models.ImageField(
- width_field="width",
- height_field="height",
- blank=True,
- null=True,
- upload_to=thumbnail_location)
- def __str__(self):
- return str(self.image.path)
- def user_post_save_receiver(sender, instance, created, *args, **kwargs):
- if instance.image:
- hd, hd_created = Thumbnail.objects.get_or_create(user=instance, type='hd')
- sd, sd_created = Thumbnail.objects.get_or_create(user=instance, type='sd')
- micro, micro_created = Thumbnail.objects.get_or_create(user=instance, type='micro')
- hd_max = (250, 250)
- sd_max = (100, 100)
- micro_max = (50, 50)
- image_path = instance.image.path
- if hd_created:
- create_new_thumb(image_path, hd, hd_max[0], hd_max[1])
- if sd_created:
- create_new_thumb(image_path, sd, sd_max[0], sd_max[1])
- if micro_created:
- create_new_thumb(image_path, micro, micro_max[0], micro_max[1])
- post_save.connect(user_post_save_receiver, sender=User)
- def create_new_thumb(image_path, instance, max_length, max_width):
- filename = os.path.basename(image_path)
- thumb = Image.open(image_path)
- size = (max_length, max_width)
- thumb.thumbnail(size, Image.ANTIALIAS)
- crop_img = Image.new('RGBA', size, (255, 255, 255, 0))
- crop_img.paste(
- thumb,
- ((size[0] - thumb.size[0]) // 2, (size[1] - thumb.size[1]) // 2))
- dir_name = os.path.dirname(os.path.abspath(image_path))
- user_id = os.path.split(dir_name)[1]
- temp_loc = "%s/users/%s/thumb/temp" % (settings.MEDIA_ROOT, user_id)
- if not os.path.exists(temp_loc):
- os.makedirs(temp_loc)
- temp_file_path = os.path.join(temp_loc, filename)
- if os.path.exists(temp_file_path):
- temp_path = os.path.join(temp_loc, "%s" % (random.random()))
- os.makedirs(temp_path)
- temp_file_path = os.path.join(temp_path, filename)
- temp_image = open(temp_file_path, "wb")
- crop_img.save(temp_image, "JPEG")
- thumb_data = open(temp_file_path, "rb")
- thumb_file = File(thumb_data)
- instance.image.save(filename, thumb_file)
- shutil.rmtree(temp_loc, ignore_errors=True)
- return True
- class EmailConfirmed(models.Model):
- user = models.OneToOneField(User)
- activation_key = models.CharField(max_length=140, null=True, blank=True)
- confirmed = models.BooleanField(default=False)
- key_expire = models.DateTimeField(default=timezone.now)
- def __str__(self):
- return str(self.confirmed)
- def activate_user_email(self):
- activation_url = "localhost:8000/password/reset/%s" % (
- self.activations_key)
- context = {
- "activation_key": self.activation_key,
- "user": self.user,
- "activation_url": activation_url
- }
- html_message = render_to_string(
- "templates/users/activation_user_message.html", context)
- subject = ''
- message = ''
- self.email_user(subject, message, settings.EMAIL_MAIN, html_message)
- def send_mail(self, subject, message, from_email=None, html_message=None):
- send_mail(subject, message, from_email, [
- self.user.email], fail_silently=False, html_message=html_message)
- class PasswordReset(models.Model):
- user = models.ForeignKey(User)
- activation_key = models.CharField(max_length=140, null=True, blank=True)
- confirmed = models.BooleanField(default=False)
- key_expire = models.DateTimeField(default=timezone.now)
- def __str__(self):
- return str(self.confirmed)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement