ABOUT ME

Konkuk.Univ 학교공부,대외활동,생활코딩,유튜브 등을 정리하는 블로그

Today
Yesterday
Total
  • 장고 읽기 구현 1
    백엔드 : 서버공부/Django 2023. 7. 29. 12:59
    728x90

    아무리 복잡한 애플리케이션도 CRUD라는 네가지 작업안에 갇혀있습니다.

    Create, Read, Update, Delete

    지금은 이 네가지 중에서 Read작업을 수행해 보겠습니다.

     

    Read는 다시 homepage와 **상세보기(article)**라는 두가지 작업으로 나눠집니다.

     

    먼저 views.py를 수정해서 기본적인 html코드를 작성해 보겠습니다.

    from django.shortcuts import render, HttpResponse
    import random
    
    # Create your views here.
    def index(request):
        return HttpResponse('<h1>Random</h1>'+str(random.random()))
    
    def create(request):
        return HttpResponse('Create')
    
    def read(request, id):
        return HttpResponse('Read!'+id)
    

    아래와 같이 수정 합니다.

    from django.shortcuts import render, HttpResponse
    import random
    
    # Create your views here.
    def index(request):
        return HttpResponse('''
    <html>
    <body>
        <h1>Django</h1>
        <ol>
            <li>routing</li>
            <li>view</li>
            <li>model</li>
        </ol>
        <h2>Welcome</h2>
        Hello, Django
    </body>
    </html>
    ''')
    
    def create(request):
        return HttpResponse('Create')
    
    def read(request, id):
        return HttpResponse('Read!'+id)
    

     

    다시 페이지를 로드해보면 아래와 같은 페이지를 확인할 수 있습니다.

    이제 아래와같은 3개의 글을 dictionary데이터 타입에 담아보도록 하겠습니다.

    				<li>routing</li>
            <li>routing</li>
            <li>routing</li>
    

     

    아래와 같은 코드를 작성해 글들을 dictionary 에 담았습니다.

    {'id':1, 'title':'routing','body':'Routing is ..'}
    {'id':2, 'title':'view','body':'View is ..'}
    {'id':3, 'title':'Model','body':'Model is ..'}
    

    그리고 이 정보들을 관리하기 위해 리스트에 담겠습니다.

    topics = [
    {'id':1, 'title':'routing','body':'Routing is ..'},
    {'id':2, 'title':'view','body':'View is ..'},
    {'id':3, 'title':'Model','body':'Model is ..'}
    ]
    

     

    그리고 아래와같이 코드를 수정해줍니다.

    from django.shortcuts import render, HttpResponse
    topics = [
    {'id':1, 'title':'routing','body':'Routing is ..'},
    {'id':2, 'title':'view','body':'View is ..'},
    {'id':3, 'title':'Model','body':'Model is ..'}
    ]
    
    def index(request):
        global topics
        ol = ''
        for topic in topics:
            ol += f'<li>{topic["title"]}</li>'
        return HttpResponse(f'''
    <html>
    <body>
        <h1>Django</h1>
        <ol>
            {ol}
        </ol>
        <h2>Welcome</h2>
        Hello, Django
    </body>
    </html>
    ''')
    
    def create(request):
        return HttpResponse('Create')
    
    def read(request, id):
        return HttpResponse('Read!'+id)
    

    위 코드는 수정사항을 반영한 전체 코드입니다.

    topics를 사용하기 위해 전역변수를 사용하였고, for topic in topics을 이용해 topics에 있는 값들을 하나하나 꺼냈습니다.

    그리고 그 값들을 이용해서 ol태그 밑에 있는 li 태그를 만들었습니다.

    그리고 <li>{topic["title"]}</li>앞에 f를 붙여서 {}를 통해 바로 변수를 사용할 수 있게하였습니다.

    다시 서버를 로드하게되면 이전과 같은 화면이 보여지게 되는것을 확인할 수 있습니다. 이전과의 차이점은 리스트들이 for문을 통해 생성된 것 이라는 점입니다.

     

    이제 아래와같이 a태그를 이용해서 링크를 걸어보겠습니다.

    ol += f'<li><a href="/myapp/read/{topic["id"]}">{topic["title"]}</a></li>'
    

    위와같이 수정한후 페이지를 로드해보면

    위와같이 링크가 생긴것을 볼 수 있습니다.

     

    각 링크를 클릭해보면

    이렇게 각각의 상세페이지로 이동하는 것을 확인할 수 있습니다.

     

    '백엔드 : 서버공부 > Django' 카테고리의 다른 글

    장고 생성 기능 구현 1  (0) 2023.07.29
    장고 읽기 구현 2  (0) 2023.07.29
    장고를 사용하는 이유  (0) 2023.07.29
    장고 라우팅  (0) 2023.07.29
    장고 앱 만들기  (0) 2023.07.29
Designed by Tistory.