django project/인스타그램

[django 인스타그램] 홈화면, TemplateView, 팔로우 게시글 목록, 인스타그램 메인 화면

지휘리릭 2020. 2. 13. 13:51

 

 

contents / views.py

홈화면에는 상단 메뉴바, 게시글 올리기, 게시물들 목록으로 구성된다. 

게시물 목록에는 내가 올린 게시물과 내가 팔로우하는 사람들의 게시물이 포함된다. 

나의 FollowRelation 객체를 가져와서 그 중에 followee 필드 값의 id들을 리스트로 만들어 followees에 저장하여 내가 팔로우하는 사람들의 정보를 구한다.

내 아이디와 위에서 구한 followee 아이디 값을 lookup_user_ids 에 저장한다.

lookup_user_ids 값으로 필터를 걸고, 그에 해당하는 게시글을 저장한다.

home.html 템플릿과 함께 context를 렌더링한다.

@method_decorator(login_required, name = "dispatch")
class HomeView(TemplateView):
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        user = self.request.user
        followees = FollowRelation.objects.filter(follower = user).values_list('followee__id', flat = True)
        lookup_user_ids = [user.id] + list(followees)
        context['contents'] = Content.objects.select_related('user').prefetch_related('image_set').filter(
            user__id__in = lookup_user_ids
        )
        return context

 

 

 

 

templates / home.html

HomeView에서 받은 contents를 화면에 출력한다.

{% extends 'base.html' %}
{% block head %}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/dropzone@5.5.1/dist/dropzone.min.css">
{% endblock %}
{% block body %}
<!--Header-->
<!--username-->
<!--Create Content-->

{% for content in contents %}
{% for image in content.image_set.all %}
<div class = "content" style = "width:600px; margin: 0 auto;">
    <div class = "post">
        <div class = "text-center user-block">
            <h5 class = "text-info left-things">{{content.user.username}}</h5>
            <img class = "img-info img-circle img-bordered-sm" src = "{{image.image.url}}" alt = "User Image" style = "width :400px; height:auto; margin: 0 auto;">
            {% endfor %}
            <div>
                <span class = "username left-things">
                    <a href = "#" class = "text-info"><b>{{content.user.username}}</b></a>
                    <a href = "#" class = "pull-right btn-box-tool"><i class = "fa fa-times"></i></a>
                </span>
            </div>
            <p>{{content.text}}</p>
        </div>
    </div>
</div>
{% endfor %}

<!--dropzone-->
<!--logoutButton-->
{% endblock %}

 

 

 

 

 

 

실행결과

비록 스크롤 캡쳐하는 법을 몰라서 따로 캡쳐했지만 자신의 게시글과 팔로우한 사람의 게시글까지 제대로 출력됐다.