IT 개발/Django

[Django] 장고, 뷰 반환타입 종류 (return type)

KADOSHOLY 2023. 12. 27. 01:53
반응형

 

Django - 장고, 뷰 반환타입 종류 (return type)

 

 

   목차

  1. 반환타입 종류 (return type)
    1. HttpResponse()
    2. render()
    3. JsonResponse()
    4. redirect() / HttpResponseRedirect()

 

 

1. 반환타입 종류 (return type)

 

1) HttpResponse() 

from django.http import HttpResponse

def testView(request):
    return HttpResponse("<h1>안녕하세요</h1>")

 

 

2) render()

from django.shortcuts import render

def testView(request):
    testtb = TestTb.objects.all()
    data = { 'number': 1,
             'string': "abc",        
             'list': ['a', 'b', 'c'],
             'dictionary': {'a': 1, 'b': 2}, 
             'mdata' : testtb }
    return render(request, 'show1.html', context=data)
<!DOCTYPE html>
<html lang="en">
<head> ... </head>
<body>
    <h3>number : {{number}}</h3>
    <h3>string : {{string}}</h3>
    <h3>list : {{list}}</h3>
    <h3>dictionary : {{dictionary}}</h3>
    {% for item in mdata %}
        <h3>id:{{item.id}}, name:{{item.name}}, age:{{item.age}}</h3>
    {% endfor %}
</body>
</html>

 

 

3) JsonResponse()

from django.http import JsonResponse
from django.forms.models import model_to_dict

def testView1(request):
    data = { 'name': 'kim', 'age': 10 }
    return JsonResponse(data)
    
def testView2(request):
    testtb = TestTb.objects.all()
    data=[]
    for t in testtb:
        t = model_to_dict(t)
        data.append(t)
    return JsonResponse(data, safe=False)

 

 

4) redirect(), HttpResponseRedirect()

    return redirect('http://naver.com')
    
    return HttpResponseRedirect('http://naver.com')

 

 

반응형