상세 컨텐츠

본문 제목

DB 정보 접근 및 장고 템플릿 내 for loop

django

by 개복신 개발자 2021. 7. 22. 14:47

본문

728x90
반응형

views.py

def hello_world(request):

    if request.method == "POST":
        text = request.POST.get('hello_world_input')

        new_hello_world = HelloWorld()
        new_hello_world.text = text
        new_hello_world.save()

        hello_world_list = HelloWorld.objects.all()

        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})

-hello_world_list에 HelloWorld.objects.all()를 할당

HelloWorld.objects.all()은 models.py에 저장되어 있는 HelloWorld의 모든 데이터를 가져온다

이 내용을 html상에 보이게 하는 코드를 작성해보자

 


hello_world.html

{% extends 'base.html' %}

{% block content%}

    <div style="height: 20rem; background-color: azure; border-radius: 1rem; margin: 2rem; text-align: center;">
        <h1 style="font-family: 'lobster', cursive;">
        Hello World List!
        </h1>

         <form action="{% url 'hello_world' %}" method="POST"> 
            <!-- action에는 적용시킬 url을 작성 -->
            {% csrf_token %}
            <div>
                <input type="text" name="hello_world_input" >
            </div>
            <div>
                <input type="submit" class="btn btn-primary " value="POST">
            </div>
        
        
        {% if hello_world_list %}
        {% for hello_world in hello_world_list %}
        <h4>
            {{ hello_world.text }}
        </h4>
        {% endfor %}
        {% endif %}
    </form>
        
    </div>
{% endblock %}

{% if hello_world_list %}
        {% for hello_world in hello_world_list %}
        <h4>
            {{ hello_world.text }}
        </h4>
        {% endfor %}
        {% endif %}

-hello_world 리스트가 존재한다면 

hello_world_list 내용을 for문으로 하나씩 화면에 보여주는 코드

 

반응형

'django' 카테고리의 다른 글

login/logout 구현  (0) 2021.08.11
회원가입 구현  (0) 2021.07.26
텍스트 작성 내용 보이기 (17강)  (0) 2021.07.19
http 프로토콜 (15~16강)  (0) 2021.07.19
models.py class 작성 (14강)  (0) 2021.07.15

관련글 더보기

댓글 영역