본문 바로가기

Django

5) Django model 사용하기!

django에서는 ORM(Object-Relational Mapping)을 지원해주는데, object를 이용해서 사용자가 SQL 쿼리문을 따로 입력할 필요 없이 데이터베이스를 사용하게 해준다. 쿼리문을 직접 확인할 수도 있다.

 

https://knackin.tistory.com/10

 

3) Django mysql 연동하기

https://knackin.tistory.com/8 1) Django 시작하기 (Windows) https://www.python.org/ Welcome to Python.org The official home of the Python Programming Language www.python.org 파이썬 홈페이지에서 파이..

knackin.tistory.com

 

app 내부의 models.py에서 모델을 생성할 수 있다.

 

from django.db import models

# Create your models here.
class TestModel(models.Model):
    name = models.CharField(max_length = 13)
    age = models.DecimalField(max_digits = 3, decimal_places = 0)

    def __str__(self):
        return self.name

 

models.Model을 상속받는 class를 작성하고 필요한 fields를 내부에 작성한다.

__str__ 메소드는 생성되는 object의 구별을 위해 사용된다.

 

간단하게 form 태그를 통해 데이터를 입력받아서 모델객체를 이용하여 DB에 저장해보자.

기존의 base.html의 sidebar를 다음과 같이 getPost 클릭시 '/getPost/'으로 이동하게 바꿔주고

 

{% block sidebar %}
        <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/getPost/">getPost</a></li>
        </ul>
{% endblock %}

 

myapp 폴더에 forms.py 파일을 추가했다.

 

from django import forms
from myapp.models import TestModel

class NameForm(forms.Form):
    name = forms.CharField(label='Your name', max_length=13)
    age = forms.DecimalField(max_digits=3, decimal_places = 0)


class TestModelForm(forms.ModelForm):
    class Meta:
        model = TestModel
        fields = ['name', 'age'] # '__all__'

 

NameForm class와 TestModelForm class를 보면 Form과 ModelForm을 각각 상속받았다는 것을 알 수 있다.

특히, NameForm의 경우 위의 TestModel과 중복되는 부분이 많은데 이렇게 모델형식을 그대로 form에서 사용할 경우에는 TestModelForm과 같이 ModelForm을 사용하여 기존 모델의 fields를 사용하는 것이 이득이다. 따라서 ModelForm을 사용하였다. (각 form 관련 class는 form 태그의 속성들을 모두 사용할 수 있다.)

 

 

그리고 getPost.html을 추가해주었다. 

주석처리된 load static은 base.html 최상단으로 옮겼다.

 

{% extends "base.html" %}
<!-- {% load static %} -->

{% block form %}
<form action="{% url 'myapp:getPost' %}" method="POST">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="OK">
</form>
{% endblock %} 

{% block message %}
{% endblock %}

{% block img %}
<img id="image" src="{% static 'img/zzzz.jpg' %}" />
{% endblock %}

 

form 태그의 action 속성에서 {% url 'myapp:getPost' %} 이란 부분이 있는데 urls.py와 관련이 있다.

 

from django.urls import path
from .views import *

app_name = 'myapp'

urlpatterns = [
    path('', index, name='index'),
    path('getPost/', getPost, name='getPost'),
    path('update/<int:id>/', update, name='update'),
    path('delete/<int:id>/', delete, name='delete'),
]

 

'myapp:getPost'의 형식을 사용하기 위해서 urls.py 내부에 app_name = 'myapp'을 추가해주어야 한다.

{{ form }} 부분이 위에서 만든 TestModelForm의 객체를 넘겨 받은 것인데 views.py에서 이루어진다.

 

from django.shortcuts import render, redirect

from myapp.models import TestModel
from myapp.forms import NameForm, TestModelForm

# Create your views here.
def index(request):
    model = TestModel.objects.all()
    return render(request, 'myapp/index.html', {'models' : model})

def getPost(request):
    if request.method == 'POST':

        # form = NameForm(request.POST)
        form = TestModelForm(request.POST)

        if form.is_valid():
            tm = TestModel(**form.cleaned_data)
            # tm.name = form.cleaned_data['name']
            # tm.age = form.cleaned_data['age']
            tm.save()
            
            return redirect('myapp:index')

    else:
        form = TestModelForm()

    return render(request, 'myapp/getPost.html', {'form': form})

def update(request, id):
    model = TestModel.objects.filter(pk=id)
    if request.method == 'POST':
        form = TestModelForm(request.POST)
        if form.is_valid():
            model.update(**form.cleaned_data)
            return redirect('myapp:index')
    else:
        form = TestModelForm()

    return render(request, 'myapp/update.html', {'model': model[0], 'form': form}) 

def delete(request, id):
    TestModel.objects.get(pk=id).delete()
    return redirect('myapp:index')

 

url '/getPost/'에 동작하는 getPost을 보면 request가 POST일 경우와 그렇지 않은 경우로 나뉜다.

POST일 경우 request.POST 객체를 이용해서 만들어둔 Form 객체를 만들어주면  fields에 맞춰 데이터를 얻을 수 있다.

데이터가 없다면 form.is_valid()의 값이 false가 되며, 데이터가 있을 경우에 모델 객체를 만들어 데이터를 넘겨준 뒤, save() 메소드로 DB에 저장해준다. form 데이터에 접근하는 방법은 cleaned_data['field명']이다. 딕셔너리 형태이므로 **를 사용하여 모델 객체에 전달해주었다. POST 데이터를 성공적으로 처리 한 후에는 항상 HttpResponseRedirect 를 반환하는 것이 관행적이다. else의 경우 빈 폼을 넘겨준다.

 

 

 

이렇게 POST를 통해 데이터를 입력받아서 model 객체로 데이터베이스에 저장하는 것 까지 완료했다.

저장된 데이터를 불러오기 위해서 index 부분을 보면 TestModel.objects.all()로 모든 데이터베이스 정보를 불러오고 'models'라는 이름으로 넘겨주었다.

 

{% block form %}
{% for model in models %}
<div>
    <h3>id:{{model.id}} {{ model.name }} {{ model.age }}  
        <a href="{% url 'myapp:update' model.id %}">수정</a>
        <a href="{% url 'myapp:delete' model.id %}">삭제</a>
    </h3>
</div>
{% endfor %}

 

index.html에서 for template을 추가하여 저장된 모든 정보를 보여주는 html을 작성하였다. (맨 우측 사진)

추가로 update와 delete 기능을 넣었다.

 

<form action="{% url 'myapp:update' model.id %}" method="POST">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="OK">
    
</form>

 

update.html 같은 경우는 getPost와 같이 form 태그를 이용해주었다. form을 통해 입력받은 데이터로 '수정'을 클릭한 아이디값에 해당하는 정보를 update 해준다. delete는 간단하게 '삭제'에 해당하는 아이디값을 조회해서 delete한다.

 

 

 

 

https://docs.djangoproject.com/en/4.1/topics/db/models/

 

Models | Django documentation | Django

Django The web framework for perfectionists with deadlines. Toggle theme (current theme: auto) Toggle theme (current theme: light) Toggle theme (current theme: dark) Toggle Light / Dark / Auto color theme Overview Download Documentation News Community Code

docs.djangoproject.com

 

'Django' 카테고리의 다른 글

7) Django to the server with fetch  (0) 2022.11.17
6) Django REST API (rest_framework)  (0) 2022.11.08
4) Django template  (0) 2022.10.25
3) Django mysql 연동하기  (0) 2022.10.18
2) Django App 만들기  (0) 2022.10.12