Django Section 10

yoodeit·2025년 8월 24일
0

일단 만드는 어무해

목록 보기
19/21

구독 구현

0) subscribeapp

python manage.py startapp subscribeapp
settings.py
urls.py path('subscribe/', include('subscribeapp.urls')),

1) subscribeapp/views.py

views.py

from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views.generic import RedirectView
from projectapp.models import Project
from subscribeapp.models import Subscription

# Create your views here.


@method_decorator(login_required,'get')
class SubscriptionView(RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        return reverse('projectapp:detail', kwargs={'pk':self.request.GET.get('project_pk')})
    
    def get(self, request, *args, **kwargs):

        project = get_object_or_404(Project, pk=self.request.GET.get('project_pk'))
        user = self.request.user
        subscription = Subscription.objects.filter(user=user,project=project)
        if subscription.exists():
            subscription.delete()
        else:
            Subscription(user=user, project=project).save()
        return super(SubscriptionView, self).get(request, *args, ** kwargs)

2) sub/models.py

from enum import unique

from django.contrib.auth.models import User
from django.db import models
from projectapp.models import Project
from pyexpat import model

# Create your models here.

class Subscription(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='subscription')
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='subscription')

    class Meta:
        unique_together = ('user', 'project')

3) migrate

4) projectapp/templates/detail.html에 susbcribe button 만들기

    <div class="text-center">
        {% if user.is_authenticated %}
        <a href="{% url 'subscribeapp:subscribe' %}?project_pk={{ target_project.pk }}">
            구독
        </a>
        {% endif %}
    </div>

5) subscribeapp/urls.py


from django.urls import path
from projectapp.views import (ProjectCreateView, ProjectDetailView,
                              ProjectListView)
from subscribeapp.views import SubscriptionView

app_name = 'subscribeapp'

urlpatterns = [
    path('subscribe/', SubscriptionView.as_view(), name='subscribe'),
    
]

6) projectapp/views.py

class ProjectDetailView(DetailView, MultipleObjectMixin):
    model = Project
    context_object_name = 'target_project'
    template_name = 'projectapp/detail.html'
    paginate_by = 25

    def get_context_data(self, **kwargs):
        project = self.object
        user = self.request.user
        if user.is_authenticated:
            subscription = Subscription.objects.filter(user=user, project=project)
        else:
            subscription = None
        object_list = Article.objects.filter(project=self.get_object())
        return super(ProjectDetailView, self).get_context_data(object_list = object_list,
                                                               subscription=subscription,
                                                               **kwargs)

7) projectapp/detail.html

    <div class="text-center mb-5">
        {% if user.is_authenticated %}
            {% if not subscription %}
            <a href="{% url 'subscribeapp:subscribe' %}?project_pk={{ target_project.pk }}"
            class="btn btn-primary rounded-pill px-4">
                구독
            </a>
            {% else %}
            <a href="{% url 'subscribeapp:subscribe' %}?project_pk={{ target_project.pk }}"
            class="btn btn-dark rounded-pill px-4">
                구독취소
            </a>
            {% endif %}
        {% endif %}
    </div>

개인이 구독한 프로젝트 볼 수 있게

1) sub/views.py

@method_decorator(login_required,'get')
class SubscriptionListView(ListView):
    model = Article
    context_object_name = 'article_list'
    template_name = 'subscribeapp/list.html'
    paginate_by = 5

    # 구독이 되어있는 아티클들만 가져와야 하기 때문이다ㅣ.
    def get_queryset(self):
        projects = Subscription.objects.filter(user=self.request.user).values_list('project')
        article_list = Article.objects.filter(project__in=projects)
        return article_list

2) templates/list.html

{% extends 'base.html' %}

{% block content %}

<div>
    {% include 'snippets/list_fragment.html' with article_list=article_list %}
</div>

{% endblock %}

3) urls.py

path('list/', SubscriptionListView.as_view(), name='list'),

4) header에 링크연결

<a href="{% url 'subscribeapp:list' %}" class="header_nav">
            <span>Sub</span>
        </a>
profile
Yoodeit

0개의 댓글