웹 프로그래밍/[ Django ]

[ Django ] 05. Django relation 1:N (사용자 분할)

kim.svadoz 2020. 8. 11. 09:57
728x90
반응형

django relation 1:N

06/22

cascade만 사용

django 확장 툴 설치

$ pip install django-extensions

settings에 등록해줘야 한다.

'django_extensions' 으로 등록

쉘창을 켠다 -> mysite 위치로 가서 켜야한다.

$ python manage.py shell_plus

ipython 설치

$ pip install ipython

0623

Admin 관리자 계정 생성

# musicians/admin.py -admin 정의
from.models import Musician, Album
admin.site.register(Musician, Alubm)
# bash 관리자계정 생성
python manage.py createsuperuser

http -> 일반적으로 상태를 저장하지 않는다.

CREATE

# 1. 댓글 생성
#인스턴스화
comment = Comment()
comment.content = '첫번째 댓글'
comment.save()

# 2. 게시글 하나 불러오기
article = Article.objects.get(pk=1)

# 2-1. comment와 article 연결하기
comment.article = article
comment.save()

# 또 다른 방법
# 작성하는 숫자는 article의 pk값
# 주의할 점 -> 참조하고자 하는 이름은 article_id로 해줘야 한다. not pk
comment.article_id = 1
comment.save()

READ

# comment 변수들 불러오기
# 1. 댓글 pk 조회
comment.pk

# 2. 댓글 content 조회
comment.content

# 3. 댓글이 어느 게시글에 연결되어 있는가
comment.article_id 

# 4. 댓글이 연결된 게시글
comment.article

# 4-1. 댓글이 연결된 게시글의 제목과 내용
comment.article.pk
comment.article.title
comment.article.content

# article의 경우는?
article.comment_set.all()
# querySet 형태로 가지고 온다

Django 사용자 분할(1:N)

  • Article 모델에 외래키 설정 후 마이그레이션 작업 진행
    • 연결할 User 모델은 settings.AUTH_USER_MODEL이다.
    • 마이그레이션 작업을 진행 시 기존의 데이터에 USER 정보가 없으므로 Default값 설정.
    • 현재 프로젝트의 admin 계정의 PK 값을 찾아 해당 값을 Default로 설정.
  • CREATE 로직 수정 & 게시글 작성자 표기
    • 게시글 생성 시 , 게시글 작성자 정보를 넣어서 저장한다.
  • UPDATE & DELETE 로직 수정
    • 사용자가 자신의 글만 수정/삭제 할 수 있도록 내부 로직 수정
    • 해당 게시글의 작성자가 아니라면, 수정/삭제 버튼이 보이지 않도록 Template 수정
  • user 모델을 외래키로 참조

image-20200624130814231

  • 해당 사용자만 수정/삭제가 가능하도록 하자

image-20200624130932120

  • 객체는 생성하지만 DB에는 반영하지 않겠다.

image-20200624131456721image-20200624134036835

  • 필요없는 field가 나오지 않도록 해주자

image-20200624131018154

  • html도 변경해주자

image-20200624131119816

메시지 출력하기

# views.py
from django.contrib import messages
messages.success(request, '게시글 작성 완료')

# base.html
<body>
  {% if messages %}
    {% for message in messages %}
      <div class="alert alert-{{ message.tags }}">
        {{ message.message }}
      </div>
    {% endfor %}
  {% endif %}
</body>

# settings.py

import os
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
    messages.ERROR : 'danger',
}

static 파일 관리하기

image

  • blank=True
    • 유효성 검사시
  • null=True
    • DB상의 컬럼에 null이 가능. TextField에서는 사용하지마세요!!
$ pip install Pillow # Python image 관리

class Article(models.Model):
    image = models.ImageField(blank=True, null=True)

$ python manage.py makemigrations
$ python manage.py migrate
  • enc type 설정하기
# form.html
<form action="" method="POST" enctype="multipart/form-data">
  {% csrf_token %}
  {% bootstrap_form form %}
  {% buttons %}
    <button type="submit" class="btn btn-primary">
      Submit
    </button>
  {% endbuttons %}
</form>
  • html 설정하기
# detail.html

{% if article.image %}
<img src="{{ article.image.url }}" alt="{{ article.image }}">
{% endif %}
  • views.py

image-20200624141816812

  • settings.py

image-20200624142952884

  • urls.py ( project )

image-20200624142716430

  • 아린

image-20200624143015990

  • 날짜별로 폴더 정리

image-20200624143251489image-20200624143349944

  • 이미지 크기를 관리하는 방법
$ pip install pilkit
$ pip install django-imagekit

# settings.py
INSTALLED_APPS = [
    'imagekit',
]

# models.py
from imagekit.models import ImageSpecField
from imagekit.processors import Thumbnail

image-20200624151337397

  • user가 저장한 사진 별로 이미지 관리를 하고 싶은 경우 models.py

image-20200624151826256

728x90
반응형