ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • django 입문(4) CRUD 기본 작업
    Backend/Django 2023. 7. 7. 00:00

    브라우저가 서버로 Data를 전달할 때 2가지 method : GET, POST

    1) Read (GET)

    <a> Tag: 기본적으로 Data를 특정 페이지(href가 가리키는 URL) 로 이동하는 동작을 수행. = GET 방식(=Server에서 Data를 가져오면서)으로 Server에 접속함.

    HTML Code를 return 하는 함수 구현: HtmlTemplate

    HttpResponse에 출력하려는 Html code(HtmlTemplate의 반환값) 를 parameter로 넘겨줌.

    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 HtmlTemplate(articleTag):
        global topics
        lis = ''
        for topic in topics:
            lis += f"<li><a href='/read/{topic['id']}/'>{topic['title']}</a></li>"
    
        return f'''
        <html>
            <head>
                <title>django-egoing</title>
            </head>
            <body>
                <h1><a href="/">Django</a></h1>
                <ul>
                    {lis}
                </ul>
                {articleTag}
            </body>
        </html>
        '''
    
    def read(request, id):
        global topics
        article = f'''
        <h2>{topics[int(id)-1]['title']}</h2>
        {topics[int(id)-1]['body']}
        '''
        return HttpResponse(HtemlTmplate(article))
    
    # Create your views here.
    def index(request):
        articel = '''
        <h2>Welcom</h2>
        Hello, Django
        '''
        return HttpResponse(HtmlTemplate(articel))
    
    def create(request):
        return HttpResponse('Create!')
    

     

    2) Create (Post)

    <form> Tag: Server로 Data를 전송하는 Tag

    속성

    • action: Data를 전송할 페이지의 URL 주소를 값으로 갖는다.(공통 부분을 제외한 URL)
    • ex. <form action=”/create/”>…</form>
    • method: “get”(default), “postpost - 브라우저가 서버로 전송하려는 Data가 숨겨짐. (payload 에서 확인 가능)
    • get - 브라우저가 서버로 전송하려는 Data가 URL에 Query string 으로 노출됨.

     

    동작 순서

    1. 사용자의 요청은 Packaging되어 HttpRequest 라는 객체로 만들어짐.
    2. Django는 요청이 들어온 URL에 따라 처리되도록 개발자가 미리 구현해 놓은 함수(ex. create, read…) 를 호출함. 이 때 parameter로 HttpRequest 객체를 전달.
    3. 호출된 함수는 HttpRequest 객체(parameter 명: request) 를 분석 후 처리하여 HttpResponse 객체를 return
    4. Django가 HttpResponse에 들어있는 정보를 브라우저에게 넘김.

    Post 방식으로 브라우저가 서버에 전달한 Data는 <HttpRequest객체>.POST[’~’] 로 접근 가능. (Dict 타입)

    redirect: 호출되는 순간 지정된 페이지로 이동시키는 함수. 주로 Data를 원하는 URL로 바로 redirect 시킬 때 사용. redirect(URL) ex. redirect(f”/read/{id}”)

    만약 redirect 하려는 URL에 parameter가 존재한다면 redirect(url, parameter) 처럼 사용하면 됨.

    csrf: Django에서 제공하는 보안 기능. 해당 기능으로 인해 서버로 Data를 송수신하는 작업에 오류가 발생할 수 있음. 이럴 때에는 @csrf.exempt 를 선언하여 해결 가능. 당연히 보안적으로는 취약점이 발생할 수 있음.

     

    3) Delete (Post)

    <input type=’hidden’>: 화면에 표시되지는 않지만 서버로 Data를 전송하는데 사용됨.

    더보기

     

    from django.shortcuts import render, HttpResponse, redirect
    from django.views.decorators.csrf import csrf_exempt
    
    topics = [
        {'id': 1,'title':'routing','body':'routing is...'},
        {'id': 2,'title':'view','body':'view is...'},
        {'id': 3,'title':'model','body':'model is...'},
    ]
    def HtmlTmplate(articleTag, id=None):
        global topics
        ContentsButton =''
    if id is not None:
            ContentsButton =f'''
            <li>
                <form action='/delete/' method='post'>
                    <input type='hidden' name='id' value={id}>
                    <input type='submit', value='delete'>
                </form>
            </li>
            <li>
                <a href="/update/{id}/">update</a>
            </li>
            '''
    
    lis =''
    for topic in topics:
            lis +=f"<li><a href='/read/{topic['id']}/'>{topic['title']}</a></li>"
    
    returnf'''
        <html>
            <head>
                <title>django-egoing</title>
            </head>
            <body>
                <h1><a href="/">Django</a></h1>
                <ul>
    {lis}
                </ul>
    {articleTag}
                <ul>
                    <li><a href="/create/">create</a></li>
    {ContentsButton}
                </ul>
            </body>
        </html>
        '''
    
    def read(request, id):
        global topics
        article =f'''
        <h2>{topics[int(id)-1]['title']}</h2>
    {topics[int(id)-1]['body']}
    '''
    return HttpResponse(HtmlTmplate(article, id))
    
    # Create your views here.
    def index(request):
        articel ='''
        <h2>Welcom</h2>
        Hello, Django
        '''
    return HttpResponse(HtmlTmplate(articel))
    
    @csrf_exempt
    def create(request):
        if request.method =='GET':
            article='''
            <form action="/create/"  method="post">
                <p><input type="text" name="title" placeholder="title"></p>
                <p><textarea name="body" placeholder="body"></textarea></p>
                <p><input type="submit"></p>
            </form>
            '''
    return HttpResponse(HtmlTmplate(article))
        elif request.method =='POST':
            newtopicid = len(topics) + 1
            newtopic = {'id': newtopicid,'title': request.POST['title'],'body':request.POST['body']}
            topics.append(newtopic)
            return redirect(f"/read/{newtopicid}")
    
    @csrf_exempt
    def delete(request):
        global topics
        if request.method =='POST':
            id = request.POST['id']
            newTopic=[]
            for topic in topics:
                if int(id) != topic['id']:
                    topic['id'] = len(newTopic) + 1
                    newTopic.append(topic)
            topics = newTopic
            return redirect('/')
    
    @csrf_exempt
    def update(request, id):
        if request.method =='GET':
            for topic in topics:
                if topic['id'] == int(id):
                    selectedTopic = topic
            article=f'''
            <form action="/update/{id}/" method="post">
                <p><input type="text" name="title" placeholder="title" value="{selectedTopic['title']}"></p>
                <p><textarea name="body" placeholder="body">{selectedTopic['body']}</textarea></p>
                <p><input type="submit"></p>
            </form>
            '''
    return HttpResponse(HtmlTmplate(article, id))
        elif request.method =='POST':
            title = request.POST['title']
            body = request.POST['body']
            for topic in topics:
                if topic['id'] == int(id):
                    topic['title'] = title
                    topic['body'] = body
            return redirect(f'/read/{id}/')

     

    참고자료

    1) 생활코딩: Python Django Web Framework(YouTube)

    2) 점프투장고: 점프 투 장고(WikiDocs)

    댓글

Designed by Tistory.