스터디 2주차 시작!!
5주차부터는 8장부터 시작하는데 본격적으로 웹페이지 개발에 들어간다.
#08
8장에서 주목한 부분 중 하나는 blog의 세부 페이지로 들어가는 방법이다.
이전에 세부페이지(detail page)로 들어갈 때는 views.py에 새로운 함수를 정의했는데, 책에서는 모델에다가 함수를 정의하는 방식을 사용한다.
이 방식으로 하면 admin페이지에서도 세부 페이지가 이동가능고, url을 모델에서 정의해서 return 하다니 신기했다.
#views.py(이전 방식)
def detail(request, blog_id):
blog_detail=get_object_or_404(Blog,pk=blog_id)
blog_hashtag=blog_detail.hashtag.all()
return render(request,'detail.html',{'blog':blog_detail, 'hashtags':blog_hashtag})
#home.html(이전 방식)
<a href="{% url 'detail' blog.id%}">...more</a>
#models.py(책)
class Post(models.Model):
title=models.CharField(max_length=30)
content=models.TextField()
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)
#author
def __str__(self):
return f'[{self.pk}]{self.title}'
def get_absolute_url(self):
return f'/blog/{self.pk}/'
#blog/index.html(책)
<h2><a href="{{ p.get_absolute_url }}">{{ p.title }}</a></h2>
또, FBV(함수형 뷰)와 CBV(클래스형 뷰)의 차이를 알았다.
FBV는 내가 직접 함수를 작성한다면, CBV는 미리 만들어 둔 함수를 가져오는 느낌?
CBV가 간단해서 편리하긴 하지만, template_name 등 제약이 있어 자세하게 작성할 떄는 FBV가 좋다. 어쨌든 기능 면에서는 큰 차이 없는 듯.
#views.py
#FBV
def single_post_page(request, pk):
post=Post.objects.get(pk=pk)
return render(request, 'blog/single_post_page.html', {'post':post, })
#CBV
class PostDetail(DetailView):
model=Post
#09
media 설정은 늘 어렵다.
pip install Pillow 잊지 말기...
media 파일 말고도 다양한 파일을 업로드 할 수 있는 FileField도 추가했다.
#10
임의의 이미지를 가져와서 사용할 수 있는 방법을 배웠다.
유용하게 쓰일 듯.
#post_detail.html
<!-- Preview Image -->
{% if post.head_image %}
<img class="img-fluid rounded" src="{{ post.head_image.url }}" alt="{{ post.title }} head_image">
{% else %}
<img class="img-fluid rounded" src="https://picsum.photos/seed/{{ post.id }}/800/200" alt="random_image">
{% endif %}
모델에 파일 이름과 파일의 확장명을 return 하는 함수를 작성하고, html에서 확장자에 따라 다르게 아이콘을 보여주는 if문을 작성했다.
방문자가 파일을 내려받을 수 있게 하는 방식도 배웠다. 생각보다 간단했다. 그냥 업로드한 파일의 url을 작성하면 된다..
#post_detail.html
<!-- Post content-->
<p>{{ post.content }}</p>
{% if post.file_upload %}
<a href="{{ post.file_upload.url }}" class="btn btn-outline-dark" role="button">Download:
{% if post.get_file_ext == 'csv' %}
<i class="fas fa-file-csv"></i>
{% elif post.get_file_ext == 'xlsx' or post.get_file_ext == 'xls' or post.get_file_ext == 'cell' %}
<i class="fas fa-file-excel"></i>
{% elif post.get_file_ext == 'docx' or post.get_file_ext == 'doc' %}
<i class="fas fa-file-word"></i>
{% elif post.get_file_ext == 'txt' %}
<i class="fas fa-file-text"></i>
{% else %}
<i class="far fa-file"></i>
{% endif %}
{{ post.get_file_name }}
</a>
{% endif %}
또, 본문(content)의 내용을 일부만 반환해서 보여주는 방식을 배웠다.
이전에 배운 방식은 요약하는 함수를 새로 작성하는 것이였는데, 이번에는 간단하게 html파일에서 작성하였다.
{{ p.content | truncatewords:45 }}
#models.py(이전 방식)
def summary(self):
return self.body[:100]
#11~12
django의 테스트 기능과 모듈에 대하여 배웠다.
테스트는 기능이 좀 더 복잡해지면 유용하게 쓰겠지만..아직은 잘 모르겠다. 그냥 문법 읽어보고 이해하는 정도.
모듈도 코드가 좀 더 간결해지는 점은 좋지만..책이랑 bootstrap의 버전이 달라서 그런가 수정하는 과정에서 많은 시간을 썼다.
참고사이트
-FBV와 CBV의 차이
01.22 - FBV를 CBV로 바꾸기 : 네이버 블로그 (naver.com)
'개인 스터디 > 정리' 카테고리의 다른 글
Do it 웹사이트 따라 만들기 - 웹사이트 만들 준비하기, 개발 환경 준비하기 (0) | 2024.01.18 |
---|---|
[Django] Do it 장고+부트스트랩 16주차 정리 (0) | 2023.03.13 |
[Django] Do it 장고+부트스트랩 13~15주차 정리 (0) | 2023.02.26 |
[Django] Do it 장고+부트스트랩 9~12주차 정리 (0) | 2023.02.20 |
[Django] Do it 장고+부트스트랩 1~4주차 정리 (0) | 2023.01.30 |