WEB/Django prac

[Django prac][HTML 10] 사용자 입력 데이터를 받아, 그대로 출력하는 서버 만들기 4

bay07 2024. 3. 14. 09:02

1. Catch를 처리하는 URLs

더보기
"""
URL configuration for firstpjt project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from articles import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    path('dinner/', views.dinner),
    path('search/', views.search),
    path('throw/', views.throw),
    path('catch/', views.catch),
]

catch라는 주소로 요청이 갔을 때, catch view 함수가 호출된다. 


2.  View 함수 작성 

# throw 페이지에서 데이터를 받는다
# 그 안에서 사용자 입력 데이터를 추출한다
# 그리고 그 데이터를 딕셔너리로 만든다.
# 그것을 템플릿에 그대로 출력하는 역할

 

그런데 어디에서 데이터를 찾아서 context를 만들어줘야할까?
사용자가 보낸 요청데이터는 어디에 있을까?
바로 모든 뷰 함수가 가지고 있는 request (요청 덩어리)


얘는 최초로 urls 파일에 있는 path('catch/', views.catch)에서 받은거
request 안에 모든 데이터가 다 들어있음 
메타데이터 (사용자 정보, 브라우저 정보 등등)
주인공은 바로 request이다. 


프린트도 한번 해보기 
    print(request)


그런데 이 print가 동작하려면 catch views 함수가 실행되어야한다. 
catch views 함수가 실행되려면 
throw 쪽에서 catch views 함수로 요청을 보내야한다. 

더보기
# 여기 주석 풀어주기
# foods 중에 랜덤으로 뽑아서 출력하려고
import random
from django.shortcuts import render


def index(request):
    context = {
        'name' : 'stella',
    }
    return render(request, 'articles/index.html', context)

def dinner(request):
    foods = [
        '사과',
        '딸기',
        '바나나',
        '감',
    ]
    picked = random.choice(foods)
    context = {
        'foods':foods,
        'picked':picked,
    }
    return render(request, 'articles/dinner.html', context)

def search(request):
    return render(request, 'articles/search.html')

def throw(request):
    return render(request, 'articles/throw.html')

# throw 페이지에서 데이터를 받는다
# 그 안에서 사용자 입력 데이터를 추출한다
# 그리고 그 데이터를 딕셔너리로 만든다. 
# 그것을 템플릿에 그대로 출력하는 역할 
def catch(request): 
    context = {
        # 그런데 어디에서 데이터를 찾아서 context를 만들어줘야할까?
        # 사용자가 보낸 요청데이터는 어디에 있을까?
        # 바로 모든 뷰 함수가 가지고 있는 request (요청 덩어리)
        # 얘는 최초로 urls 파일에 있는 path('catch/', views.catch)에서 받은거
        # request 안에 모든 데이터가 다 들어있음 
        # 메타데이터 (사용자 정보, 브라우저 정보 등등)
        # 주인공은 바로 request이다. 
        # 프린트도 한번 해보기 
        print(request)
        # 그런데 이 print가 동작하려면 catch views 함수가 실행되어야한다. 
        # catch views 함수가 실행되려면 
        # throw 쪽에서 catch views 함수로 요청을 보내야한다. 
        
    }
    return render(request, 'articles/catch.html',context)

3.  throw.html 작성 

    <form action="http://127.0.0.1:8000/catch/" method="GET">
    <form action="/catch/" method="GET">

 

둘 다 똑같은 코드이기 때문에,

둘 중에 하나 원하는 걸 골라서 하면 된다.

{% extends "articles/base.html" %}

{% block content %}
    {% comment %} method는 기본값이라 써도 되고 안써도 됨 {% endcomment %}
    <h1> Throw </h1>
    <form action="http://127.0.0.1:8000/catch/" method="GET">
      <input type="text" name="message">
      <input type="submit">
    </form>


{% endblock content %}

 


4. 지금 실행해보면 메세지

 

페이지는 지금 중요하지 않고, 

왼쪽의 실행결과를 보자 

 

확대하면, 이 메세지이다. 

<WSGIRequest: GET '/catch/?message=hello'>

 

 


5. 메세지 한번 타입 찍어보자  dir

 

보니까 클래스 타입이다.

클래스에 있는 요소들을 더 볼 수 있는 건 dir 명령어

print(dir(request))

 

 


6. 쩜(.)으로 한번 더 들어가보자

print(request.GET)

 

 

<QueryDict: { 'message' : [ 'hello' ] }>

get이라는 속성의 값은 QueryDict이다.

처음 들어보는 것. 이건 그냥 장고에서 내부적으로 사용하는 용어 

중요한 건 Dict,  Dictionary라는 것

그리고 오른쪽 값이 Key Value라는 것이다. 

 [ 'hello' ] 

 

 


7. 결국 .. 딕셔너리에 접근하면 된다 !

request.GET.get('message')

 

print(request.GET.get('message'))

 

다시 hello를 제출하면 

 

hello가 출력된다.

['hello'] 이건 리스트는 아니다.

최종적으로 접근하면 나중에 값이 풀린다

크게 생각하지 않아도 됨

request.GET.get('message')

여기까지 가야 through에서 준 데이터에 접근할 수가 있는 것이다.