주뇽's 저장소
5. DB 연동 본문
728x90
반응형
- account/model.py 코드 수정
from django.db import models
# Create your models here.
class HelloWorld(models.Model):
text = models.CharField(max_length=25, null=False)
- migrate 명령어로 앱이 필요로 하는 테이블 생성
python manage.py makemigrations
python manage.py migrate
- 쉘 스크립트를 이용하여 데이터베이스에 데이터 저장 및 조회
python manage.py shell
- 앱에 있는 모델 import
from accountapp.models import HelloWorld
- HelloWorld 모델로 모델 데이터 만들기
from django.utils import timezone
q = HelloWorld(text = "HelloWorld")
q.save()
객체가 생성된 다음 q.save()를 입력하면 모델 데이터가 데이터베이스에 저장된다.
- 모델 데이터의 값 조희
q.id #-- id 조회
#-- 출력 : 1
#-- 장고는 데이터 생성 시 데이터에 id값을 자동으로 넣어준다.
HelloWorld.objects.all() #-- 저장된 모든 데이터 조회
quit()
GET, POST 확인
- 확인을 위한 GET, POST 버튼 생성
{% extends 'base.html' %}
{%block content%}
<div style="height: 20rem; background-color:darkgreen; border-radius: 1rem; margin: 2rem">
<h1 style="font-family: 'Indie Flower', cursive; ">
TEST
</h1>
<form action="/account/hello_world/", method="post">
{% csrf_token %}
<!-- <div>
<input type = "text" name = "account_input">
</div> -->
<div>
<input type = "submit" class = "btn btn-primary" value="POST">
</div>
</form>
<form action="/account/hello_world/", method="get">
{% csrf_token %}
<!-- <div>
<input type = "text" name = "account_input">
</div> -->
<div>
<input type = "submit" class = "btn btn-primary" value="GET">
</div>
</form>
<h1> {{text}}</h1>
</div>
{% endblock %}
- method에 맞게 View 처리
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def hello_world(request):
if request.method == "POST":
return render(request, "accountapp/hello_world.html", context={"text" : "POST!!!"})
else:
return render(request, "accountapp/hello_world.html", context={"text" : "GET!!!"})
- 결과 확인
GET 버튼 클릭
POST 버튼 클릭
'웹개발 > Django' 카테고리의 다른 글
6. AccountApp - Sign Up ⇒ Create View (0) | 2023.08.25 |
---|---|
4. CSS 개념 및 설정 (0) | 2023.08.19 |
3. Style, 구글 폰트를 통해 Header, Footer 꾸미기 (0) | 2023.08.19 |