django 3. CRUD 기능 구현

dev-somi·2022년 1월 17일
0

django

목록 보기
2/13

1. CRUD란?

Create
Read
Update
Delete

모든 어플리케이션들은 이 기능을 구현한다.

2. Read 구현하기 (views.py)

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

내가 담고 싶은 내용들을 딕셔너리로 만들고 딕셔너리를 쉽게 담을 수 있는 topics이라는 리스트로 구성했다.

def HTMLTemplate(articleTag, id=None):
global topics
for topic in topics:
ol += f'<l.i><a href="/read/{topic["id"]}"> {topic["title"]}</l.i>'

return f'''
<html>
<body>
    <h1><a href="/">Django</a></h1>
    <ol>
        {ol}
    </ol>
    {articleTag}
    <ul>
        <li><a href="/create/">create</a></li> 
        {contextUI}
    </ul>
</body>
</html>
'''

HTMLTemplate(): 다른 함수에도 재사용하는 코드를 이 함수 내에 담았다. 이 프로젝트의 전체 웹페이지를 보여주는 함수

def index(request):
article = '''

<h2>Welcome</h2>
Hello, Django
'''
return HttpResponse(HTMLTemplate(article))

  • 기본 경로로 접속 했을 때만 hello, Django 글자가 보여줬으면 하기 때문에 이를 article 변수에 담는다. 그리고 index에 라우팅 되었을 때 HTMLTemplate(article) 인자를 전달해주고 위의 HTMLTemplate 함수가 article 변수를 articleTag로 받는 구조...
    - 말로 하니까 설명이 좀 어렵다

따라서 해당 경로로 접속하면 위의 화면이 프린트 된다.

3. read 상세보기 구현하기

def read(request, id):
global topics
article = ''
for topic in topics:
if topic["id"] == int(id):
article = f'<h.2>{topic["title"]}</h.2>{topic["body"]}'

return HttpResponse(HTMLTemplate(article, id))
  • url로 들어온 id 파라미터 타입은 문자열이기 때문에 int로 변환
  • 만약 내가 read/1 링크를 클릭했다면 id 값인 1과 동일한 id를 가진 딕셔너리를 topics 리스트에서 찾는다.
  • 따라서 발견된 딕셔너리의 title 값과 body 값을 article이라는 변수에 저장한다.
  • 마지막으로 HTMLTemplate 함수에 article 인자를 전달해주어서 화면에 출력한다.

4. form 기능 구현하기

홈 화면에 create (글 생성 기능)을 추가하려고 한다.

def HTMLTemplate():

<ul>
        <li><a href="/create/">create</a></li> 
</ul>

def create(request):
return HttpResponse('Create')

아까 생성했던 HTMLTemplate 함수 밑에 create 화면을 추가한다.
따라서 /create/ 링크로 이동하면 Create라고 쓰여진 화면을 볼 수 있다.
귀찮아서 캡쳐는 안 함

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(HTMLTemplate(article))
  • 글을 작성하는 양식을 만들기 위해서 input 태그 사용 (안 닫아도 됨)
  • 무엇을 입력하는지 사용자에게 알려주고 싶다면 placeholder를 사용
  • name=title을 지정해주면 입력한 데이터를 나중에 서버로 전송할 때 title이라는 이름을 부여해서 전송
  • p 태그를 통해서 단락을 나타냄
  • textarea는 여러 줄의 텍스트를 입력할 때 사용 (닫아야 함)
  • submit이라는 type을 통해서 제출 버튼 생성
  • 입력 받은 데이터를 서버에 원하는 path로 전송하기 위해서는 form 태그로 감싸야 한다. (원하는 경로는 action이라는 속성에 추가)

0개의 댓글