vs코드에서 django 시작하기
- python -m venv venv
- venv\Scripts\Activate
- pip install django
- pip install autopep8 (참고) : 파이썬 코드를 PEP8 컨벤션에 맞게 자동으로 교정해주는 모듈
- pip install pylint (참고) : 오류 확인을 도와준다
- pip install pylint_django (참고) : pylint가 발생시키는 에러메시지를 해결해준다
- django-admin startproject 프로젝트명 . : . 프로젝트명의 새로운 폴더를 만들지 않고 현재 경로에서 작업하겠다
- (django-admin startproject 프로젝트명 : 프로젝트명의 새로운 폴더를 만들고 작업하겠다)
- python manage.py startapp 앱 (=django-admin startapp 앱)
[settings.py]
[INSTALLED_APPS] : 앱 추가
AUTH_USER_MODEL = 'user.UserModel'
models.py
아래 두 줄은 같다
product = models.ForeignKey (Product, on_delete=models.CASCADE, unique=True)
product = models.OneToOneField (Product, on_delete=models.CASCADE)
>>> OneToOne 관계일 때 related_name을 사용한 역참조가 용이하다
amount = models.PositiveIntegerField("입고수량") : 양수만 입력 가능
DateTimeField
created_at = models.DateTimeField(auto_now_add=Ture) : 객체가 생성될 때만 생성
updated_at= models.DateTimeField(auto_now=Ture) : 객체가 생성&수정될 때 생성
python manage.py makemigrations : migrations 폴더에 파일 생성(0001_initial.py, 변경 사항 기록), db에 저장X
python manage.py migrate : 변경사항을 db에 저장O
views.py
회원가입
from django.http import HttpResponse
from django.contrib.auth import get_user_model
if get_user_model().objects.filter(username=username).exists(): # .exists() : True/False로 알려줌
return HttpResponse("이미 존재하는 username입니다.")
user = get_user_model().objects.create(username=username)
user.set_password(password) # 패스워드 암호화
user.save()
return HttpResponse("회원가입 성공")
로그인
#로그인 확인 함수
user = authenticate(request, username=username, password=password)
if not user:
return HttpResponse("존재하지 않는 계정이거나 비밀번호가 일치하지 않습니다.")
#로그인 함수
login(request, user)
return HttpResponse("로그인 성공")
#로그아웃 함수
logout(request)
return HttpResponse("로그아웃 성공")
get과 filter의 차이
# 무조건 하나만 존재해야 함. 아니면 에러 발생.
# unique 필드나 pk 키에 사용.
try:
User.objects.get(username=username)
except:
print("사용자가 존재하지 않습니다.")
# 개수 상관없이 QuerySet으로 반환해 줌.
try:
User.objects.filter(username=username)
except:
print("사용자가 존재하지 않습니다.")
@login_required : 함수 실행 전 user의 로그인 체크
@transaction.atomic : 실행 중 error 발생시 db 생성 안 됨
request.POST : 딕셔너리의 형태
code = request.POST.get("code", "") : "" 공백의 기본값은 None이기 때문에 get() 사용시 에러가 발생하지 않는다
django rest framework(DRF) 사용시 훨씬 간단하게 쓸 수 있다
form(django)의 상위 호환 -> serializer(django rest framework)
FBV(Function Base View)
def user_view(request):
if request.method == "GET":
pass
elif request.method == "POST":
pass
elif request.method == "PUT":
pass
elif request.method == "DELETE":
pass
CBV(Class Base View)
class UserView(APIView):
def get(self, request):
def post(self, request):
def put(self, request):
def delete(self, request):
urls.py
path의 차이
# 프로젝트 urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('accounts.urls')),
path('', include('erp.urls')),
]
#account 앱 urls.py
from django.urls import path
from . import views
urlpatterns = [
path('signup/', views.signup_view, name='sign-up'), # /accounts/signup/
path('login/', views.login_view, name='log-in'), # /accounts/login/
]
#erp 앱 urls.py
from django.urls import path
from . import views
urlpatterns = [
path('inboundcreate/', views.inbound_create, name='inbound-create'), # /inboundcreate/
path('inboundlist/<int:id>/', views.inbound_list, name='inbound-list'),# /inboundlist/<int:id>/
]
python manage.py runserver
Postman API Platform | Sign Up for Free
Postman is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs—faster.
www.postman.com
Postman을 통해 html 없이도 response와 db 저장 등 테스트 가능
'Django' 카테고리의 다른 글
Django ImageField 저장 안 될 때 enctype (0) | 2023.04.13 |
---|---|
ImportError: cannot import name 'config' from 'decouple' (0) | 2023.04.11 |
Django 3주차 숙제_댓글 불러오기 쓰기 삭제하기_메서드 (0) | 2023.04.06 |
Django 기초 5주차 2_taggit_Sparta Coding Club (0) | 2023.04.06 |
Django 기초 5주차 1_기능 추가_Sparta Coding Club (0) | 2023.04.05 |