3,803 바이트 추가됨
, 2021년 10월 29일 (금) 16:45
== 개요 ==
프로필은 또 다른 DB 요청이 있다는 점에서 불필요한 과정이 늘기도 하지만... SNS 계정을 한 프로필 내에서 관리하기 위해 사용해본다.
그리고, 일단 간단하다.
== 모델작성 ==
기본적으로 프로필 모델을 작성하고 다음과 같이 1:1 연결을 하는 것이 일반적이다.<syntaxhighlight lang="python">
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
</syntaxhighlight>일반적인 프로필 모델이라면 위 과정만으로도 구현이 끝난다.
다만, 이번엔 여러 계정을 하나의 프로필에 엮어줄 예정이라, AbstractBaseUser를 이용하여 다음과 같은 방식으로 짜주자.<syntaxhighlight lang="python">
class User(AbstractBaseUser): # 사용자들..!!
# 계정관련
identifier = models.CharField(max_length=20, unique=True, null=True, blank=False) # 로그인 할 때 사용할 식별자.
email = models.EmailField(max_length=60)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) # 연결할 프로필모델. 아래에서 정의.
# 프로필이 사라지면 사용자 모델도 한꺼번에 다 없어지게끔!
# 유저권한 관련
is_active = models.BooleanField(default=True) # 장고 필수필드. 이게 false면 로그인 자체가 안됨.
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False) # 장고 필수필드
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'identifier' # 어떤 것을 로그인 때의 식별자로 사용할 것인가.
REQUIRED_FIELDS = ['email', ] # 입력할 때 필수입력 필드 지정.
def __str__(self):
return self.email#self.nickname +'.' +self.identifier
def has_perm(self, perm, obj=None): # 이건 뭐람;;?
return self.is_admin
def has_module_perms(self, app_label):
return True
objects = AccountManager() # 회원가입을 다루는 클래스.
</syntaxhighlight>그리고 프로필 계정은 필요에 따라 다음과 같이 짠다.<syntaxhighlight lang="python">
class Profile():
'''계정모델에서 연결하여 상위에 있는, 하위 SNS계정을 종합하는 프로필.'''
# 유저정보 관련
username = models.CharField(max_length=10) # 실명을 기입하게끔 하자.
nickname = models.CharField(max_length=10, unique=True, null=True, blank=False) # 드러날 식별자. 변경 가능하지만, 유일하다.
date_joined = models.DateTimeField(auto_now_add=True)
last_login = models.DateTimeField(auto_now=True)
email_active = models.BooleanField(default=False) # 이메일 검증여부
</syntaxhighlight>이렇게 하면 user.profile.username 같은 방식으로 프로필 속성에 접근할 수 있다.
== 계정에서 프로필 생성 ==
회원가입 후 프로필을 생성하여야 한다.
=== 탬플릿 추가 ===
base.html 등에 프로필이 없는 경우, 프로필을 생성하고 활동할 수 있게끔 코드를 넣는다.<syntaxhighlight lang="html+django">
{% if user.profile %}
{% else %}
<div class="alert alert-danger">
<h1><strong>프로필을 등록해야 글을 쓸 수 있습니다.</strong></h1>
<h2><a href="{% url 'membership:create_profile' %}">프로필 생성</a></h2>
</div>
{% endif %}
</syntaxhighlight>
=== url 추가 ===
다음과 같이 url을 추가해준다.<syntaxhighlight lang="python">
path('create_profile/', views.create_profile, name='create_profile'),
</syntaxhighlight>
=== view 추가 ===
다음과 같이 뷰를 추가한다.<syntaxhighlight lang="python">
@login_required()
def create_profile(request):
pass
</syntaxhighlight>
[[분류:장고 기능구현(초급)]]