from datetime import timezone
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
class UserManager(BaseUserManager):
def create_user(self, id, email, nickname, password=None):
if not id:
raise ValueError('Users must have an ID')
if not email:
raise ValueError('Users must have an email address')
user = self.model(
id=id,
email=self.normalize_email(email),
nickname=nickname,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, id, email, nickname, password=None):
user = self.create_user(
id=id,
email=email,
nickname=nickname,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
id = models.CharField(primary_key=True, max_length=15, unique=True)
email = models.EmailField(default='', max_length=50, unique=True)
nickname = models.CharField(default='', max_length=30)
profile_image = models.ImageField(upload_to='profile_images/', null=True, blank=True) # 프로필 이미지
is_expert = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'id'
REQUIRED_FIELDS = ['email', 'nickname']
def __str__(self):
return self.id
@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
# Create your models here.
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') # 작성자
content = models.TextField(max_length=280, blank=True) # 트윗 내용 (텍스트)
image = models.ImageField(upload_to='post_images/', null=True, blank=True) # 첨부 이미지 (선택적)
created_at = models.DateTimeField(auto_now_add=True) # 생성일
likes_count = models.PositiveIntegerField(default=0) # 좋아요 개수
replies_count = models.PositiveIntegerField(default=0) # 답글 개수
def __str__(self):
return f'{self.user.nickname} - {self.content[:30]}'
class Meta:
ordering = ['-created_at'] # 최신 포스트부터 정렬
#TODO: 댓글에 대한 답글 기능 구현, 이미지 포함 답글 기능 구현
class Comment(models.Model):
content = models.TextField() # 답글 내용
created_at = models.DateTimeField(auto_now_add=True) # 답글 생성일
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') # 답글이 속한 포스트
def __str__(self):
return f'Comment by {self.post.user.nickname} on {self.post.content[:30]}'
class Meta:
ordering = ['created_at'] # 답글은 오래된 것부터 정렬