데이터베이스와 연결하는 django의 편의기능이다.
app의 models.py가 생성되었을테니 거기로 들어가 class를 만들어준다.
from django.db import models
# Create your models here.
class Helloworld(models.Model):
text = models.CharField(max_length=255, null=False)
거기에 이런 식으로 적어준 다음에 python manage.py를 이용해서 makemigrations - > migrate 해주면 적용이 된다.
loalhost/account/helloworld/에 접근하면 띄우도록 설정한 html 파일 helloworld.html에 들어가서 form 태그를 만들어준다.
form 태그 안에는 input 태그를 만들어준다.
<form action="/account/helloworld/" method="post">
{% csrf_token %}
<input type="submit" class="btn btn-primary" value="POST">
</form>
이 때, form action 부분에 helloworld 뒤에 슬래시(/)를 붙여주지 않으면 runtimeerror가 난다. 주의를 요한다.
helloworld(request):
#return HttpResponse('hello')
if request.method == "POST":
return render(request, 'accountapp/helloworld.html', context={'text': 'POST METHOD desu'})
else:
return render(request, 'accountapp/helloworld.html', context={'text': 'GET METHOD desu'})
이런 식으로 요청이 post였으면 post라고 보이게, get이었으면 get으로 보이게끔. 그럼 이 return한 context는 html상에 어떻게 띄우느냐...
<h1>
{{ text }}
</h1>
이런 식으로 템플릿문법을 사용해주면 된다.
그럼 페이지에 접근하자마자는 이런 식으로 뜨다가...

post 버튼을 누르면 글자가 바뀐다.

<form action="/account/helloworld/" method="post">
{% csrf_token %}
<div>
<input type="text" name="helloworld_input">
</div>
<input type="submit" class="btn btn-primary" value="POST">
</form>
폼태그 안에 인풋태그 하나 더 넣어서 type은 text로, 구분자는 helloworld_input으로 만들어줍니다.

views.py에서 처리할 때
models.py 에서 만들어둔 객체 helloworld를 import하여 새로 하나 만들자.
from accountapp.models import Helloworld
new_helloworld = Helloworld();
이제 views.py 안에서 new_helloworld라는 객체가 존재.
이 안에 input 받은 내용을 넣어줍시다.
temp = request.POST.get('helloworld_input')
new_helloworld.text = temp
new_helloworld.save()
post요청에서 helloworld_input이라는 이름으로 받은 내용을 temp에 임시 저장했다가, 그것을 new_helloworld객체의 text 필드에 담아줍니다. 그 후에 저장한다.
return render(request, 'accountapp/helloworld.html', context={'helloworld_output': new_helloworld})
렌더링되는 내용이 객체가 되었으니 수정합니다.
{% if helloworld_output %}
<h1>
{{ helloworld_output.text}}
</h1>
{% endif %}
템플릿언어로 if문을 사용해서 helloworld_output.text 를 출력하도록 함.

리다이렉트를 안해주면 그 주소로 재접속하지 않는 이상, 새로고침할 때마다 계속 post요청이 들어가면서 똑같은 내용들이 post된다. 이걸 방지하기 위해 post 이후에는 리다이렉션을 통해 get요청을 하도록 해줘야 함.

이런 식으로 url 이름을 지정해준 바 있기 떄문에 이걸 활용한다.
여기서 강의와 달라서 에러가 났다. app_name 이어야 함...

이렇게 수정해주고.
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
리다이렉트 관련 모듈들을 임포트해온 뒤에...

return을 다음과 같이 수정해주면 된다.