DAY 2 Django

김의석 ·2023년 12월 29일

Django

목록 보기
2/39

생성기능 구현

form

    <ul>
        <li><a href="/create/">create</a></li>
    </ul>
  • 생성 기능을 구현할 create로 이동하는 링크 만들기
    • ul : 순서가 없는 HTML 리스트를 정의할 때 사용한다.
    • href="/create/" : 현재 url에서 /create/로 이동하는 링크
@csrf_exempt
def create(request):
    global nextId
    print('request.method' , request.method)
    
    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(HTMLTemplete(article))
  • views.py의 create 함수에서 form 태크를 추가
    • form : 태그 내의 내용을 특정 server로 전송할 때 사용
      • action = "/create/" : 내용을 전송할 url 지정
      • method = "POST" or "GET" : 보낼 내용을 POST 혹은 GET으로 전송할 수 있다
    • input type = text : text를 입력 받을 수 있다.
      • name = title : 사용자가 입력한 값이 서버에 전송 될 때 입력 값이 'title'이다 라는 의미.
        즉 tittle = 입력값.
      • placeholder = title : input type 창에 title을 띄움.
    • p : 단락을 나타내는 태그
    • textarea : 글의 본문을 작성하는 태그.
      여러줄의 텍스트를 입력할 때 사용한다.
    • input type = submit : 서버로 전송하기 위한 버튼을 생성.
    • 참고
      • 웹라우저에서 오른쪽 클릭 후 검사 후 network 태크에서 웹브라우저와 server 사이에 어떤 요청으로(GET,POST) 주고 받는지를 확인 할 수있다.

method=GET,POST

request response object

  elif request.method == "POST":
        title = request.POST['title']
        body = request.POST['body']
        newTopic = {"id":nextId, "title":title, "body":body}
        topics.append(newTopic)
        url = '/read/'+str(nextId)
        nextId = nextId + 1
        return redirect(url)
  • POST 요청의 처리
    • request.method : 요청이 POST / GET인지 확인할 수 있다.
    • request.POST : POST의 내용을 가져올 수 있다.
      이때에는 create에서 입력한 값 title과 body를 dict 형태로 가져온다.
    • redirect
      redirect(to, permanent=False, *args, **kwargs)
      to 에는 어느 URL 로 이동할지를 정하게 됩니다.
      단지 URL로 이동하는 것이기 때문에 render 처럼 context 값을 넘기지는 못합니다.
      URL 로 이동한다는 건 그 URL 에 맞는 views 가 다시 실행 됨을 의미.
profile
널리 이롭게

0개의 댓글