본문 바로가기
App Programming/Django

[Django] CRUD

by goatlab 2023. 2. 17.
728x90
반응형
SMALL

CRUD (Create, Read, Update, Delete)

 

CRUD는 대부분의 컴퓨터 소프트웨어가 가지는 기본적인 데이터 처리 기능인 Create (생성), Read (읽기), Update (갱신), Delete (삭제)를 묶어서 일컫는 말이다. 사용자 인터페이스가 갖추어야 할 기능 (정보의 참조/검색/갱신)을 가리키는 용어로서도 사용된다.

 

home.html

 

update와 delete가 추가된 home.html을 만든다.

 

{% extends 'main.html' %}

{% block content %}
<h1>Home Template</h1>

<div>
    <a href="{% url 'create-room' %}">Create Room</a>

    <div>
        {% for room in rooms %}
            <div>
                <a href="{% url 'update-room' room.id %}">Edit</a>
                <a href="{% url 'delete-room' room.id %}">Delete</a>
                <span>@{{room.host.username}}</span>
                <h5>{{room.id}} -- <a href = "{% url 'room' room.id %}">{{room.name}}</a></h5>
                <small>{{room.topic.name}}</small>
                <hr>
            </div>

        {% endfor %}
    </div>
    
</div>

{% endblock content %}

 

room_form.html

 

{% extends 'main.html' %}

{% block content %}

<div>
    <form method = "POST" action = "">
        {% csrf_token %}
        {{form}}
        <input type = "submit" value = "Submit"/>
    </form>
</div>

{% endblock content %}

 

{{form}}를 {{form.as_p}}로 바꿔주면 최근순으로 갱신한다.

 

delete.html

 

templates의 base 폴더에 delete.html을 추가한다.

 

{% extends 'main.html' %}

{% block content %}

<form method="POST" action="">
    {% csrf_token %}
    <p>Are you sure you want to delete "{{obj}}"?</p>
    
    <a href="{{request.META.HTTP_REFERER}}">Go Back</a>
    <input type="submit" value="Confirm" />
</form>

{% endblock content %}

 

forms.py

 

from django.forms import ModelForm
from .models import Room

class RoomForm(ModelForm):
    class Meta:
        model = Room
        fields = '__all__'

 

models.py

 

from django.db import models
from django.contrib.auth.models import User

class Topic(models.Model):
    name = models.CharField(max_length = 200)
    
    def __str__(self):
        return self.name

class Room(models.Model):
    host = models.ForeignKey(User, on_delete = models.SET_NULL, null = True)
    topic = models.ForeignKey(Topic, on_delete = models.SET_NULL, null = True)
    name = models.CharField(max_length = 200)
    description = models.TextField(null = True, blank = True)
    # participants =
    updated = models.DateTimeField(auto_now = True)
    created = models.DateField(auto_now_add = True)
    
    class Meta:
        ordering = ['-updated', 'created']
    
    def __str__(self):
        return self.name
    
class Message(models.Model):
    user = models.ForeignKey(User, on_delete = models.CASCADE)
    room = models.ForeignKey(Room, on_delete = models.CASCADE)
    body = models.TextField()
    updated = models.DateTimeField(auto_now = True)
    created = models.DateField(auto_now_add = True)
    
    def __str__(self):
        return self.body[0:50]

 

views.py

 

from django.shortcuts import render, redirect
from .models import Room
from .forms import RoomForm

def home(request):
    rooms = Room.objects.all()
    context = {'rooms': rooms}
    
    return render(request, 'base/home.html', context)

def room(request, pk):
    room = Room.objects.get(id = pk)

    context = {'room': room}
    
    return render(request, 'base/room.html', context)

def createRoom(request):
    form = RoomForm()
    if request.method == 'POST':
        form = RoomForm(request.POST)
        if form.is_valid():
            form.save()
            
            return redirect('home')
    
    context = {'form': form}
    
    return render(request, 'base/room_form.html', context)

def updateRoom(request, pk):
    room = Room.objects.get(id = pk)
    form = RoomForm(instance = room)
    
    if request.method == 'POST':
        form = RoomForm(request.POST, instance = room)
        if form.is_valid():
            form.save()
            
            return redirect('home')
    
    context = {'form': form}
    return render(request, 'base/room_form.html', context)

def deleteRoom(request, pk):
    room = Room.objects.get(id = pk)
    if request.method == 'POST':
        room.delete()
        return redirect('home')
    
    return render(request, 'base/delete.html', {'obj':room})

 

urls.py

 

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name = "home"),
    path('room/<str:pk>/', views.room, name = "room"),
    
    path('create-room/', views.createRoom, name = "create-room"),
    path('update-room/<str:pk>/', views.updateRoom, name = "update-room"),
    path('delete-room/<str:pk>/', views.deleteRoom, name = "delete-room")
]

 

728x90
반응형
LIST

'App Programming > Django' 카테고리의 다른 글

[Django] 기본 요소 (1)  (0) 2023.02.20
[Django] Search (검색 기능)  (0) 2023.02.17
[Django] Admin (Room)  (0) 2023.02.17
[Django] 템플릿 (Templates) (2)  (0) 2023.02.02
[Django] 템플릿 (Templates) (1)  (0) 2023.02.01