728x90

이글은 완전 기초적인 CRUD 구현방법에 대해 설명해드린느 글입니다.

 


CRUD란?

📥 Create : 데이터 생성
👀 Read : 데이터 불러오기
✍️ Update : 데이터 수정 / 갱신
📤 Delete : 데이터 삭제하기

 

 

 

<1.시작>

#1.장고설치 
pip install django
#2. 장고 프로젝트만들기
django-admin startproject config .
#3. 데이터베이스DB 생성
python manage.py migrate
#4. 앱생성
python manage.py startapp myapp

 

 

<2.프로젝트 구성>

>

 

3. 소스코드

#myproject/urls.py

from django.contrib import admin
from django.urls import path , include

#사용자가 사이트에 접속했을떄 요청을 어떻게 누가 처리할건지 지정하는 
#라우팅을 해주는 파일 

# https://127.0.0.1/
# https://127.0.0.1/app/
# https://127.0.0.1/create/
# https://127.0.0.1/read/1/
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('myapp.urls'))
]
#myapp/urls.py

#장고의 urls.py 파일은 페이지 요청이 발생하면 가장 먼저 호출되는 파일로 
#URL과 뷰 함수 간의 매핑을 정의한다. 뷰 함수는 views.py 파일에 정의된 함수를 말한다.
# 본 프로젝트에서는 글생성, 읽기, 삭제, 수정 이 있기때문에 4개의 path를 추가해주었다.

from django.contrib import admin
from django.urls import path , include
from myapp import views

urlpatterns = [
    path('',views.index),
    path('create/',views.create),
    path('read/<id>/',views.read),
    path('delete/' , views.delete),
    path('update/<id>/',views.update)
    
]

 

#myapp/views.py

from django.shortcuts import render, HttpResponse
import random
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import redirect
nextId = 4
topics = [
{'id':1, 'title':'routing', 'body':'Rounting is ..'},
{'id':2, 'title':'view', 'body':'view is ..'},
{'id':3, 'title':'model', 'body':'model is ..'}
]

def HTMLTemplate(articleTag,id=None):
    
    global topics
    ol = ''
    contextUI =''
    if id != None:
        contextUI = 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>

    '''

    for topic in topics:
        ol +=  f'<li><a href = "/read/{topic["id"]}">{topic["title"]}</a></li>'
    
    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>
                                      
    ''')

def index(request):
    article = '''
    <h2> Welcome</h2>
    Hello Django
    '''

    return HttpResponse(HTMLTemplate(article))

def read(request,id):
    global topics
    article =''

    for topic in topics:
        if topic['id'] == int(id):
            article = f'<h2>{topic["title"]}</h2>{topic["body"]}'

    return HttpResponse(HTMLTemplate(article,id))

@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" placeholder="title" name="title"> </p>
                <p> <textarea name="body" placeholder="body"> </textarea> </p>
                <p> <input type="submit"></p>
            </form>
        '''
        return HttpResponse(HTMLTemplate(article))
    elif request.method =='POST':
        title = request.POST['title']
        body = request.POST['body']

        newtopic = {"id":nextId , "title":title, "body":body}

        url = '/read/' + str(nextId)
        nextId = nextId + 1
        topics.append(newtopic)
        return redirect(url)
    
@csrf_exempt
def delete(request):
    global topics

    if request.method == 'POST':
        id = request.POST['id']
        newTopics = []
        for topic in topics:
            if topic['id'] != int(id):
                newTopics.append(topic)
        topics = newTopics
        return redirect('/')
    
@csrf_exempt
def update(request,id):
    global topics
    if request.method == 'GET':

        for topic in topics:
            if topic['id'] == int(id):
                selectedTopic ={
                    "title":topic['title'],
                    "body":topic['body']
                }
        article = f'''
            <form action ="/update/{id}/" method="post">
                <p> <input type="text" name="title" placeholder="title"></p>
                <p> <textarea name="body" placeholder="body">{selectedTopic['body']}</textarea></p>
                <p> <input type="submit"></p>
            </form>
        '''
        return HttpResponse(HTMLTemplate(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}')

 

<4. 결과화면 >

 

 

< 5.느낀점 >

Django를 처음 공부하면서 배우는건데 파이썬과 웹작동방식을 조금 알고있으니 빨리 빨리 이해되는거같다.

html css db이용해서 웹페이지 게시판을 처음 구현할때 1주일이 넘는시간이 걸렸던거같은데.... 

 

쨋든 개발을 다하고나서 글쓰기에 <script>alert('test')</script> 스크립트문을 넣었더니 그대로 실행되더라... 보안적인 부분은 아직 장고라는 프레임워크를 배우는단계라 고민만 해보고 다음 단계로 넘어가야겠다. 

728x90

'Python > Django' 카테고리의 다른 글

파이썬 Django 웹 개발 환경준비하기  (0) 2023.09.06

+ Recent posts