여름의 서재

[Django] 장고 기초_MTV 디자인 패턴 본문

Skill/Django

[Django] 장고 기초_MTV 디자인 패턴

엉아_ 2021. 9. 5. 23:00
728x90

1) Model

: 응용 프로그램의 데이터 구조를 정의하고 DB의 기록을 관리 (=model)

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

-> Article이라는 테이블 안에 title, content, created_at, updated_at 등의 다양한 필드를 만듦.

 

- 다양한 필드 타입

 

1. CharField(max_length=None, **options)

: 최대 길이의 제한이 있는 문자열 필드

 

2. TextField(**options)

: 길이 제한이 없고 많은 양의 텍스트일 경우 사용

 

3. DateTimeField(auto_now=False, auto_now_add=False, **options)

: auto_now=True -> 객체가 저장될 때마다 매번 자동으로 필드에 현재 시간이 입력된다.

: auto_now_add=True -> 객체가 처음 생성될 때 자동으로 현재 시간이 입력된다.

 

4. DecimalField(max_digit=None, decimal_places=None)

: max_digits -> 숫자에 허용되는 최대 자릿수

: decimal_places -> 숫자와 함께 저장될 소수 자릿수

 

2) Template

: 파일의 구조나 레이아웃을 정의

: 실제 내용을 보여주는데 사용 (=view)

{% extends "base_generic.html" %}

{% block title %}{{ section.title }}{% endblock %}

{% block content %}
<h1>{{ section.title }}</h1>

{% for story in story_list %}
<h2>
  <a href="{{ story.get_absolute_url }}">
    {{ story.headline|upper }}
  </a>
</h2>
<p>{{ story.tease|truncatewords:"100" }}</p>
{% endfor %}
{% endblock %}

 

- Built-in template tags and filters

 

1. comment

: {% comment %}와 {% endcomment %}있는 모든 문장들은 코멘트로 처리되고 무시하게 된다.

{% comment "Optional note" %}
    <p>Commented out text with {{ create_date|date:"c" }}</p>
{% endcomment %}

 

2. for

: 반복문

{% for article in articles %}
	<h1>{{ article.title }}</h1>
{% endfor %}

 

3. extends

: 해당 템플릿이 상속받을 부모 템플릿을 지정한다.

{% extends "base.html" %}

 

4. block

: 하위 템플릿에서 재지정(overriden)할 수 있는 블록을 정의

{% block content %}
{% endblock content %}

 

5. filter

: Built-in filter reference

https://docs.djangoproject.com/ko/3.2/ref/templates/builtins/#title

 

3) View

: HTTP 요청을 수신하고 응답을 반환

: Model을 통해 요청을 충족시키는데 필요한 데이터에 접근

: template에게 응답의 서식 설정을 맡김 (=controller)

def index(request):
    return render(request, 'index.html')

 

Comments