models.py
2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import os
from django.db import models
from django.conf import settings
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
class UserManager(BaseUserManager):
def create_user(self, email, password, **extra_fields):
if not email:
raise ValueError('email field required')
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.is_admin = True
user.save()
return user
def profile_image_path(instance, filename):
return 'profile_image/{email}.jpeg'.format(email=instance.email)
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True, max_length=255)
nick_name = models.CharField(default='', max_length=20)
profile_image = models.ImageField(blank=True, upload_to=profile_image_path)
region = models.IntegerField(default=-1)
period = models.IntegerField(default=0)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def save(self, *args, **kwargs):
super(User, self).save(*args, **kwargs)
def delete(self, using=None, keep_parents=False):
try:
os.remove('profile_image/{email}.jpeg'.format(email=self.email))
except FileNotFoundError:
pass
super(User, self).delete()
def __str__(self):
return '{email}'.format(email=self.email)
@property
def is_staff(self):
return self.is_admin
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)