Django

[Django] 9. CRUD with functions

개발자 뭄뭄 2022. 9. 21. 00:04
반응형


1. READ

articles/views.py

# articles/views.py

from django.shortcuts import render
from .models import Article
# Create your views here.

def index(request):
    articles = Article.objects.all()
    context = {
        'articles':articles
    }
    return render(request,'articles/index.html', context)

articles/templates/articles/index.html

# articles/templates/articles/index.html
{% extends 'base.html' %}

{% block content %}
    <h1>index</h1>
    <hr>
    {% for article in articles %}
    {{article.pk}} 번째 게시물<br>
    제목 : {{article.title}} <br>
    내용 : {{article.content}} <br>
    <hr>
    {% endfor %}
{% endblock content %}

http://127.0.0.1:8000/articles/에 접속하면 다음과 같은 화면이 나온다.

2. CREATE

  1. 새로운 내용을 입력받을 form을 만들 ‘NEW’와
  1. 입력받은 내용을 DB로 보낼 ‘CREATE’가 필요하다.
  • 마찬가지로 수정의 흐름은 urls.pyviews.py → templates 의 순서이다.
# articles/urls.py

from django.urls import path
from . import views

app_name = "articles"
urlpatterns = [
    path('',views.index,name="index"),
    path('new/',views.new,name="new"),
		# 이부분을 추가했습니다!
    path('create/',views.create,name="create"),
]
# articles/views.py

from django.shortcuts import render, redirect
from .models import Article
# Create your views here.

def index(request):
    articles = Article.objects.all()
    context = {
        'articles':articles
    }
    return render(request,'articles/index.html', context)

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

# 이부분을 추가했습니다!
def create(request):
    title = request.POST.get("title")
    content = request.POST.get("content")
    article = Article(title=title, content=content)
    article.save()
		# 작성한 후에는 redirect를 통해서 index로 돌아오게 만든다.
    return redirect("articles:index")
# articles/templates/articles/new.html
# 새로운 내용을 입력받을 form 을 new.html에 생성한다.

{% extends 'base.html' %}

{% block content %}

<form action="{% url 'articles:create' %}" method="POST">
    {% csrf_token %}
    <label for="title">Title:</label>
    <input type="text" id="title" name="title">
    <div>
        <label for="content">Content:</label>
        <br>
        <textarea name="content" id="content" cols="30" rows="10"></textarea>
        
    </div>
    <input type="submit">
</form>

{% endblock content %}
  • index page에서 새로운 글을 작성할 수 있도록 <a> 를 추가한다.
# articles/templates/articles/index.html
{% extends 'base.html' %}

{% block content %}
    <h1>index</h1>
    <a href="{% url "articles:new"%}"> 새 글 작성하기</a>
    <hr>
    {% for article in articles %}
    {{article.pk}} 번째 게시물<br>
    제목 : {{article.title}} <br>
    내용 : {{article.content}} <br>
    <hr>
    {% endfor %}
{% endblock content %}

3. READ - DETAIL

  • 각 게시물 마다 내용을 자세히 읽고, 수정 및 삭제할 수 있는 page 를 만든다.
  • 마찬가지로 수정의 흐름은 urls.pyviews.py → templates 의 순서이다.

# articles/urls.py

from django.urls import path
from . import views

app_name = "articles"
urlpatterns = [
    path('',views.index,name="index"),
    path('new/',views.new,name="new"),
    path('create/',views.create,name="create"),
		# 이부분을 추가했습니다!
    path('<int:pk>/',views.detail,name="detail"),
]
# articles/views.py

from django.shortcuts import render, redirect
from .models import Article
# Create your views here.

def index(request):
    articles = Article.objects.all()
    context = {
        'articles':articles
    }
    return render(request,'articles/index.html', context)

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

def create(request):
    title = request.POST.get("title")
    content = request.POST.get("content")
    article = Article(title=title, content=content)
    article.save()
    return redirect("articles:index")
# 이부분을 추가했습니다!
def detail(request, pk):
    article = Article.objects.get(pk = pk)
    context = {
        'article':article
    }
    return render(request, 'articles/detail.html',context)
# articles/templates/articles/detail.html
{% extends 'base.html' %}

{% block content %}
{{article.pk}} 번째 게시물입니다.
<hr>
<p>제목: {{article.title}} </p>
<p>내용 : {{article.content}} </p>
<p>작성시간 : {{article.created_at}} </p>
<p>수정시간 : {{article.updated_at}} </p>
<a href="{% url 'articles:index' %}">뒤로가기</a>
{% endblock content %}
  • 인덱스 페이지에서 각 게시글의 detail page로 이동할 수 있는 태그를 달아준다.
# articles/templates/articles/index.html
{% extends 'base.html' %}

{% block content %}
    <h1>index</h1>
    <a href="{% url "articles:new"%}"> 새 글 작성하기</a>
    <hr>
    {% for article in articles %}
    {{article.pk}} 번째 게시물<br>
    제목 : {{article.title}} <br>
    내용 : {{article.content}} <br>
    <a href="{%url "articles:detail" article.pk %}">자세히보기</a>
    <hr>
    {% endfor %}
{% endblock content %}

4. DELETE

  • 마찬가지로 수정의 흐름은 urls.pyviews.py → templates 의 순서이다.
  • 삭제한 후에는 index 화면으로 리다이렉트 되게 만들었다.
# articles/urls.py

from django.urls import path
from . import views

app_name = "articles"
urlpatterns = [
    path('',views.index,name="index"),
    path('new/',views.new,name="new"),
    path('create/',views.create,name="create"),
    path('<int:pk>/',views.detail,name="detail"),
		# 이부분을 추가했습니다!
    path('<int:pk>/delete/',views.delete,name="delete"),
]
# articles/views.py

from django.shortcuts import render, redirect
from .models import Article
# Create your views here.

def index(request):
    articles = Article.objects.all()
    context = {
        'articles':articles
    }
    return render(request,'articles/index.html', context)

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

def create(request):
    title = request.POST.get("title")
    content = request.POST.get("content")
    article = Article(title=title, content=content)
    article.save()
    return redirect("articles:index")

def detail(request, pk):
    article = Article.objects.get(pk = pk)
    context = {
        'article':article
    }
    return render(request, 'articles/detail.html',context)

# 이부분을 추가했습니다!
def delete(request, pk):
    article = Article.objects.get(pk=pk)
    article.delete()
    return redirect("articles:index")
  • 각 게시글의 detail 화면에서 삭제할 수 있도록 만들었다.
# articles/templates/articles/detail.html
{% extends 'base.html' %}

{% block content %}
{{article.pk}} 번째 게시물입니다.
<hr>
<p>제목: {{article.title}} </p>
<p>내용 : {{article.content}} </p>
<p>작성시간 : {{article.created_at}} </p>
<p>수정시간 : {{article.updated_at}} </p>
<a href="{% url 'articles:index' %}">뒤로가기</a>
# 이부분을 추가했습니다.
<a href="{% url 'articles:delete' article.pk%}">삭제하기</a>
{% endblock content %}
  • index 화면에서도 바로 삭제할 수 있도록 만들었다.
# articles/templates/articles/index.html

{% extends 'base.html' %}

{% block content %}
    <h1>index</h1>
    <a href="{% url "articles:new"%}"> 새 글 작성하기</a>
    <hr>
    {% for article in articles %}
    {{article.pk}} 번째 게시물<br>
    제목 : {{article.title}} <br>
    내용 : {{article.content}} <br>
    <a href="{%url "articles:detail" article.pk %}">자세히보기</a>
		# 이부분을 추가했습니다.
    <a href="{%url "articles:delete" article.pk %}">삭제하기</a>
    <hr>
    {% endfor %}
{% endblock content %}

5. UPDATE

  1. 게시글을 수정할 ‘edit’
  1. 수정한 게시글을 DB에 올릴 ‘update’
# articles/urls.py
from django.urls import path
from . import views

app_name = "articles"
urlpatterns = [
    path('',views.index,name="index"),
    path('new/',views.new,name="new"),
    path('create/',views.create,name="create"),
    path('<int:pk>/',views.detail,name="detail"),
    path('<int:pk>/delete/',views.delete,name="delete"),
		# 이 부분을 추가했습니다.
    path('<int:pk>/edit/',views.edit, name="edit"),
    path('<int:pk>/update/',views.update, name="update"),
]
# articles/views.py

from django.shortcuts import render, redirect
from .models import Article
# Create your views here.

def index(request):
    articles = Article.objects.all()
    context = {
        'articles':articles
    }
    return render(request,'articles/index.html', context)

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

def create(request):
    title = request.POST.get("title")
    content = request.POST.get("content")
    article = Article(title=title, content=content)
    article.save()
    return redirect("articles:index")

def detail(request, pk):
    article = Article.objects.get(pk = pk)
    context = {
        'article':article
    }
    return render(request, 'articles/detail.html',context)

def delete(request, pk):
    article = Article.objects.get(pk=pk)
    article.delete()
    return redirect("articles:index")

# 아래 부분을 추가했습니다.
def edit(request, pk):
    article = Article.objects.get(pk=pk)
    context={
        'article':article
    }
    return render(request, 'articles/edit.html',context)

def update(request, pk):
    article = Article.objects.get(pk=pk)
    article.title = request.POST.get("title")
    article.content = request.POST.get("content")
    article.save()
    return redirect("articles:detail", article.pk)
# articles/templates/articles/edit.html

{% extends 'base.html' %}

{% block content %}

<form action="{% url 'articles:update' article.pk %}" method="POST">
    {% csrf_token %}
    <label for="title">Title:</label>
    <input type="text" id="title" name="title" value={{article.title}}> 
    <div>
        <label for="content">Content:</label>
        <br>
        <textarea name="content" id="content" cols="30" rows="10">
            {{article.content}}
        </textarea>
        
    </div>
    <input type="submit">
</form>

{% endblock content %}

  • detail 페이지와 index 페이지에서도 바로 수정이 가능하도록 추가합니다
    # detail.html
    
    {% extends 'base.html' %}
    
    {% block content %}
    {{article.pk}} 번째 게시물입니다.
    <hr>
    <p>제목: {{article.title}} </p>
    <p>내용 : {{article.content}} </p>
    <p>작성시간 : {{article.created_at}} </p>
    <p>수정시간 : {{article.updated_at}} </p>
    <a href="{% url 'articles:index' %}">뒤로가기</a>
    <a href="{% url 'articles:delete' article.pk%}">삭제하기</a>
    
    # 아래 부분을 추가했습니다.
    <a href="{% url 'articles:edit' article.pk%}">수정하기</a>
    {% endblock content %}
    # index.html
    
    {% extends 'base.html' %}
    
    {% block content %}
        <h1>index</h1>
        <a href="{% url "articles:new"%}"> 새 글 작성하기</a>
        <hr>
        {% for article in articles %}
        {{article.pk}} 번째 게시물<br>
        제목 : {{article.title}} <br>
        내용 : {{article.content}} <br>
        <a href="{%url "articles:detail" article.pk %}">자세히보기</a>
        <a href="{%url "articles:delete" article.pk %}">삭제하기</a>
    
    		# 아래부분을 추가했습니다.
        <a href="{%url "articles:edit" article.pk %}">수정하기</a>
        <hr>
        {% endfor %}
    {% endblock content %}

    최종 완성 페이지!


Uploaded by N2T

반응형