2024. 5. 7. 15:04

2024. 4. 30. 16:20

템플릿 태크 {% csrf_token %}는 다음과 같이 렌더링되는

 

숨겨진 필드를 생성

 

<input type="hidden" name="csrfmiddlewaretoken" value="26jk2cEtV9z4JIEHXal/>

 

CSRF의 자세한 내용은 다음을 참고한다

 

https://owasp.org/www-community/attacks/csrf

2024. 4. 26. 17:52

1. pip install django-cors-headers

 

2. settings.py 

 

INSTALLED_APPS = [

  'corsheaders'

]

 

3. MIDDLEWARE = [

  'corsheaders.middleware.CorsMiddleware', 

]

 

4. CORS_ALLOWED_ORIGINS = [

  'http://localhost:5173' # 보내는 클라이언트 주소

]

 

5. CORS_ALLOW_CREDENTIALS = True

 

 

2024. 4. 26. 14:18

 

pip install djangorestframework

pip install djangorestframework-simplejwt

2024. 4. 25. 10:52

 

AbstractUser 에서 관리자 계정 생성할 때 username 입력 에러 나서

username 항목에 

 

null = True,

 

default = ' '

 

를 넣어주면 된다

2024. 4. 19. 14:27

1. gmail 로그인

 

2. 설정 - 보안 - 

 

 

from django.core.mail import EmailMessage

email = EmailMessage('title', 'content', to=['apple@gmail.com'])

email.send()

 

 

smtplib.SMTPServerDisconnected: 

Connection unexpectedly closed

 

발생하는 이유

 

SSL을 True로 설정해야 한다

SSL을 True로 설정하면 TLS는 False로 설정해야 한다

 

둘 중 하나만 True가 되어야 한다

 

 

2024. 3. 11. 17:35

settings.py에 다음을 추가한다

 

APPEND_SLASH=False

2024. 3. 11. 15:27

http://localhost:5173 does not match any trusted origins.): /auth/login/

 

이런 메세지가 떴을 때는

 

settings.py 에 다음을 넣어준다

 

CSRF_TRUSTED_ORIGINS = ['http://localhost:5173']

2024. 3. 8. 16:49

X-CSRFToken

2024. 3. 8. 15:10

1. pip freeze > requirements.txt
a. pip freeze 는 현재 설치되어 있는 python 라이브러리 목록 표시
  b. requirements.txt 에 목록을 써서 배포할 때 표시
  c. github에 requirements.txt 커밋
2. settings.py에서 ALLOWED_HOSTS = ['*'] 로 표시
3. 리눅스에서 다음 명령어 실행
  a. sudo apt update
  b. sudo apt upgrade
  c. sudo apt install build-essential, pip3, python3
  d. sudo pip3 install --upgrade pip
4.홈 디렉토리에 소스코드 다운로드
  a. git clone https://github.com/xxxx
5. 가상환경 생성
  a. sudo apt install virtualenv
  b. virtualenv -p python3 venv
  c. source venv/bin/activate
6. 패키지 설치
  a. pip install -r requirements.txt
  b. 설치하다가 pkg-config 없다고 에러나면 pkg-config 설치
    i. sudo apt install pkg-config
  c. 설치하다가 Command ‘pkg-config --exists mariadb' 뜨면 default-libmysqlclient-dev 설치
    i. sudo apt install default-libmysqlclient-dev
7. 서버 실행
    a. python manage.py runserver 0.0.0.0:8000
    b. 확인 후 종료
8. 웹서버와 연결할 uwsgi 설치
    a. pip install uwsgi
9. uwsgi.ini 작성 후 저장
    a. vi uwsgi.ini
    b. chdir=/home/ubuntu/{프로젝트폴더}
    module={프로젝트내 파일이름}.wsgi:application
    master=True
    pidfile=/tmp/project-master.pid
    vacuum=True
    max-requests=5000
    daemonize=/home/ubuntu/{프로젝트폴더}/django.log
     home=/home/ubuntu/{프로젝트 폴더}/venv
     virtualenv=/home/ubuntu/pybo/venv
     socket=/home/ubuntu/{프로젝트 폴더}/uwsgi.socket
     chmod-socket=666
     프로젝트 폴더 - manage.py가 있는 경로 디렉토리 이름
     프로젝트 내 파일 이름 - settings.py 가 있는 경로 디렉토리 이름


     c. chdir=/home/leejae/pybo
     module=icube.wsgi:application
     master=True
     pidfile=/tmp/project-master.pid
     vacuum=True
     max-requests=5000
     daemonize=/home/leejae/pybo/django.log
     home=/home/leejae/pybo/venv
     virtualenv=/home/leejae/pybo/venv
     socket=/home/eejae/pybo/uwsgi.socket
     chmod-socket=666

          i. xcube2 내의 pybo 디렉토리 안에 icube 프로젝트 생성시 작성
     d. uwsgi --ini uwsgi.ini 입력
          [uWSGI] getting INI configuration from uwsgi.ini 뜨면 통신 정상
10. nginx 설치
     a. sudo apt install nginx
11. nginx.conf 수정
     a. sudo vi /etc/nginx/nginx.conf
     http {
     upstream django {
          server unix:/home/leejae/pybo/uwsgi.sock;
     }
}
입력
     c. uwsgi 사용하면 uwsgi.sock 생성 후 nginx 하고 연결됨
12. default 수정
     a. sudo vi /etc/nginx/sites-enabled/default
     b. location / {
          include /etc/nginx/uwsgi_params;
          uwsgi_pass django;
}
          location /static/
               alias /home/xcube2/pybo/pybo/static;
}
          location /media/ {
               alias /home/leejae/pybo/pybo/media;
}
13. nginx 재시작
     a. sudo service nginx restart
14. python 서버 실행 - 외부 접속을 위해 0:8000 으로 시작해야 함

    a. python manage.py runserver 0:8000
15. 접속 후 확인

2024. 3. 4. 16:57

python -m pip3 install --upgrade pip

2024. 2. 28. 15:35

1. 인증 담당 앱 생성

 

python manage.py startapp xauth

 

2. INSTALLED_APPS 에 xauth 등록

 

INSTALLED_APPS = [

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

    'xauth'

]

 

3. xauth.models.py 에서 AbstractUser를 상속받아 XUser 생성

class XUser(AbstractUser):

  nation = models.CharField(max_length=50)

  USERNAME_FIELD = "email"

 

4. settings.py 에 AUTH_USER_MODEL 등록

AUTH_USER_MODEL = 'xauth.XUser'

5. xauth.admin.py 에서 Admin 에 XUser 등록

admin.site.register(XUser)

 

6. DB 테이블 생성

python manage.py makemigrations

 

python manage.py migrate

 

7. urls.py 에 auth 경로 작성

from django.contrib import admin

from django.urls import path, include


urlpatterns = [

    path('admin/', admin.site.urls),

    path('auth/', include('xauth.urls'))

]

 

8. xauth.urls.py 작성

urlpatterns = [

  path('login/', views.loginx, name="loginx"),

  path('logout/', views.logoutx, name="logoutx"),

  path('signup/', views.signupx, name="signupx")

]

 

9. 회원가입 코드 생성

def signupx(request):

  if request.method == "POST":

    username = request.POST['username']

    password = request.POST['password']

    email = request.POST['email']

    nation = request.POST['nation']


    user = User.objects.create_user(username, email, password)

    user.nation= nation

    user.save()

    return redirect('users:login')

10. login 코드 생성

def loginx(request):

  if request.method == "POST":

    post = request.POST

    email = post['email']

    password = post['password']

    user = authenticate(username=email, password=password)

    if user is not None: # login success

      res = login(request, user)

      print(f'res : {res}')

      print('auth success~!')

    else:

      print('auth failed~!')

 

11. logout 코드 생성

def logoutx(request):

  logout(request)

  return redirect('users:login')

12. 버그 수정

XUser 에서 email로 로그인을 하기 위해

 

USERNAME_FIELD 를 설정하면 버그 발생한다

 

AbstractUser 에서 변경해야 함

 

1. email 항목 unique 추가

email = models.EmailField(_("email address"), unique=True, blank=True)

 

2. REQUIRED_FILEDS 에서 email 삭제

#REQUIRED_FIELDS = ["email"]

 

3. createsuperuser 실행할 때 버그 수정

 

AbstractUser 클래스에서

REQUIRED_FIELDS = ["username"]

항목 추가

 

12. 로그인 로그아웃 테스트

2024. 2. 28. 15:00

settings.py 에서

 

LANGUAGE_CODE = 'ko-kr'

 

TIME_ZONE = ''Asia/Seoul"

 

로 변경

2024. 2. 28. 09:20

users_user 테이블의 username이 유일하지 않다

즉 중복 입력했다 이런 뜻이다

 

 

2024. 2. 22. 10:07

 

wheel 을 동작하다가 pkg-config 를 못찾겠어서 나온 버그

 

pkg-config 를 설치해주면 된다

 

pip install pkg-config

 

에러 메세지는 길더라도 차분히 읽어봐야 한다