개발일기 [Python 파이썬]

Django MTV 사용하기

neullo 2024. 4. 18. 21:15

 📢 데이터베이스에서 모든 아티클을 조회해서 /articles/에서 볼 수 있도록 해봅시다!

 

  1. view에서 model에 접근해 모든 아티클 가져오기
  2. view에서 가져온 아티클을 template으로 넘기기
from .models import Article
...

def articles(request):
    articles = Article.objects.all()
    context = {
        "articles": articles,
    }
    return render(request, "articles.html", context)
    
 ...

 

 

3. template에서 넘어온 context 보여주기

{% extends "base.html" %}

{% block content %}
    <h1>Articles</h1>

    <ul>
        {% for article in articles %}
            <li>
                <div>글 번호 : {{ article.id }}</div>
                <div>글 제목 : {{ article.title }}</div>
                <div>글 내용 : {{ article.content }}</div>
                <br>
            </li>
        {% endfor %}
    </ul>

{% endblock content %}

 

4. view에서 템플릿을 랜더링해서 리턴