
POST 요청으로 받은 Form Data를 DB에 저장하고, DB에 저장된 모든 text 리스트를 노출한다.
accountapp > views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from accountapp.models import HelloWorld
def hello_world(request):
if request.method == "POST":
text = request.POST.get("hello_world_input")
# DB 저장
new_hello_world = HelloWorld()
new_hello_world.text = text
new_hello_world.save()
hello_world_list = HelloWorld.objects.all()
return render(request, 'accountapp/hello_world.html', context={'hello_world_list': hello_world_list})
hello_world.html 일부
{% if hello_world_list %}
{% for hello_world in hello_world_list%}
<h4>
{{ hello_world.text }}
</h4>
{% endfor %}
{% endif %}

Redirect 사용HttpResponseRedirect가 있다.HttpResponseRedirect는 사용자의 브러우저를 주어진 URL로 redirect하기 위해 사용되는 HTTP 응답 클래스이다. django의 view함수에서 URL로의 redirect를 처리할 때 주로 사용된다.HTTP 302 코드를 반환한다. POST후 redirect하는 패턴 :POST/Redirect/GET 패턴이라고 한다.reverse() 메서드를 사용하여 URL을 동적으로 생성하는 것이 좋다. 이 방법은 URL 패턴이 변경될 때 유연하게 대응할 수 있다.accountapp > views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from accountapp.models import HelloWorld
def hello_world(request):
if request.method == "POST":
text = request.POST.get("hello_world_input")
# DB 저장
new_hello_world = HelloWorld()
new_hello_world.text = text
new_hello_world.save()
return HttpResponseRedirect(reverse('accountapp:hello_world'))
else:
hello_world_list = HelloWorld.objects.all()
return render(request, 'accountapp/hello_world.html', context={'hello_world_list': hello_world_list})
accountapp > urls.py
from django.urls import path
from accountapp.views import hello_world
app_name = "accountapp"
urlpatterns = [
path('hello_world/', hello_world, name='hello_world')
]
urls.py 에서 app_name="accountapp" 설정해주었고, views.py의 hello_world 함수를 path('hello_world/', hello_world, name='hello_world')와 같이 명칭해주었기 때문에 reverse('accountapp:hello_world')가 해당 URL을 찾을 수 있게 된 것.
reverse 함수 테스트
print(reverse('accountapp:hello_world'))
/account/hello_world/