18강 DB 정보 접근 및 장고 템플릿 내 for loop
hello_world.html
{% extends 'base.html' %}
{% block content %}
<div style="border-radius: 1rem; margin: 2rem; text-align: center">
<h1 sytle="font-family: 'lobster', cursive;">
Hello World LIST!
</h1>
<form action="/account/hello_world/" method="post">
{% csrf_token %}
<div>
<input type="text" name="hello_world_input">
</div>
<div>
<input type="submit" class="btn btn-primary" value="POST">
</div>
</form>
<!--#if 에서 for문을 돌린다.-->
{% if hello_world_list %}
{% for hello_world in hello_world_list %}
<h4>
{{ hello_world.text }}
</h4>
{% endfor %}
{% endif %}
</div>
{% endblock %}
views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
# Create your views here.
#view 단의 완성
from django.urls import reverse
from accountapp.models import HelloWorld
def hello_world(request):
if request.method == "POST":
# 포스트가 완료한이후에 겟으로 되돌아가서 남아있는 글들을 지울 수 있게한다.
temp = request.POST.get("hello_world_input")
new_hello_world = HelloWorld()
new_hello_world.text = temp
new_hello_world.save()
hello_world_list = HelloWorld.objects.all() #헬로월드에 모든 데이터를 다 긁어온다.
return HttpResponseRedirect(reverse('accountapp:hello_world'))
# 포스트가 완료한이후에 겟으로 되돌아가서 남아있는 글들을 지울 수 있게한다. redirect
# URL에서 ACCOUNT를 가져온다. 해당 경로를 만들어줄 함수를 쓴다
else:
hello_world_list = HelloWorld.objects.all()
return render(request, 'accountapp/hello_world.html',
context={'hello_world_list': hello_world_list})
#view는 만들었고 이제 route해줘야한다.
#특정 주소를 만들어 주는 작업이 필요하다.
urls.py
from django.urls import path
from accountapp.views import hello_world
app_name = 'accountapp'
#"127.0.0.1:8000/account"
#왜 어카운트앱안에 있는데 또 다시 만드냐
#저위에 라우트를 매번 쓸수 없기에 기능을 사용해서 헬로월드라는 곳으로 바로가라는 함수를
#사용할 수 있다.
urlpatterns = [
path('hello_world/', hello_world, name = 'hello_world')#롸우터의 이름
]
models.py
from django.db import models
# Create your models here.
class HelloWorld(models.Model):
text = models.CharField(max_length=255, null=False)
새로고침을 해도 for문이 작동하지 않는다.
'Computer Science > Django_pinterest' 카테고리의 다른 글
210819 장고 20강 CRUD 소개 (0) | 2021.08.19 |
---|---|
210819 장고 19강 디버깅 (0) | 2021.08.19 |
210819 장고 17강 POST 통신을 이용한 DB 데이터 저장 실습 (0) | 2021.08.19 |
210818 장고 16강 GET, POST 프로토콜 실습 (0) | 2021.08.19 |
20210818 장고 핀터레스트 14강Model, DB 연동,~15강 서버와 통신하는 HTTP 프로토콜 메서드 중에서도 GET, POST (0) | 2021.08.18 |