AI 웹개발반/Python, Django

[Django] 06 회원가입, 로그인기능 수정하기

째깍단 2023. 4. 6. 00:06

1) 회원가입 수정하기

 

from django.contrib.auth import get_user_model
#db에 사용자명이 있는지 확인하는 기능... 숙제...?

get_user_model 모듈로

간단히 db에서 사용자명이 있는지 검사해볼 수 있다.

 

 

아래는 숙제에서 작성해보았던 코드

#내가 작성한 코드
name_check = UserModel.objects.filter(username=username)

#예제 코드 get_user_model 모듈을 사용해 db에 있는 사용자를 확인해준다
exist_user = get_user_model().objects.filter(username=username)

 

 

 

 create_user() 내장함수로  유저 정보를 간단히 저장해줄 수 있다.

 

아래 5줄을 1줄로.......

new_user = UserModel()

new_user.username = username

new_user.password = password

new_user.bio = bio

new_user.save()  # 저장

 

#new_code
UserModel.objects.create_user(username=username, password=password, bio=bio)

 

 

 

 

 

 

2) 로그인 기능 + 로그인 후 home 띄우기

 

 

auth, 사용자 기능을 import하고 기본기능들을 활용해보자

from django.contrib import auth

 

 

authenticate()

암호화한 password를 비교해주고, 사용자 이름까지 적절한지 비교해주는 모듈

 

 

auth.login(request, me)  #요청값, 사용자 정보

auth.logout()

login(), logout() 기능도 내장되어 있다!

 

 

위치 잘 보며 폴더 만들고 home.html을 추가한다.

templates > tweet(새 폴더)

templates > tweet > home.html

 

 

user = request.user.is_authenticated

is_authenticated  로그인 했는지 확인하기

True값을 갖는다.

 

+ 공식문서에 False값을 가지는 반대 개념의 함수도 있다!

is_annoymous 

 

 

*** 오늘의 배움.. 내장함수에는 ()가 안붙는 경우도 있다!

     이것때문에 오류가 생겨서 한참 헤메다 튜터님 도움 받음..

*** 함수에 ()가 붙는지 안붙는지는 django 기본문서를 활용하여 공부하자

https://docs.djangoproject.com/en/4.2/ref/contrib/auth/

 

 

 

위의 작업이 끝나면 if문으로 로그인 했을 때 보여지는 home기능을 GET으로 연결한다.

if request.method == 'GET':
    return render(request, 'tweet/home.html')

 

요청.method에 GET기능을 부여해 html을 불러오기

 

 

 

전체 urls.py에 path를 추가해주면 tweet페이지가 생긴다!     #중요_빼먹지 않기

path('', include('tweet.urls')),

 

 

 

- 새롭게 설정한 경로를 따라가보자..

if 로그인 True:
    return redirect('/')

>> / 만 있으면 기본 페이지로 이동

 

 

# 127.0.0.1:8000 과 views.py 폴더의 home 함수 연결
path('', views.home, name='home'),

>>path에 있는 ''이 '/'기본 페이지를 뜻함

>> home 함수의 기능이 적용되는중

 

 

def home(request):
    if #로그인했는지 Is_authenticated()로 검사후
        return redirect('/tweet') #True면 home
    else:
        return redirect('/sign-in') #False면 로그인화면

>> 페이지를 조건에따라 반환해줌!