Backend/Django

django 25. Mixin 소개 및 Commentapp 구현

meong_j 2021. 10. 12. 14:41
728x90
반응형

Commentapp

python manage.py startapp commentapp
  • commentapp App생성

 

Settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bootstrap4',
    'accountapp',
    'profileapp',
    'articleapp',
    'commentapp',
]
  • 생성한 commentapp 추가 등록

 

urls.py

from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include

from pragmatic import settings

urlpatterns = [

    path('admin/', admin.site.urls),
    path('accounts/', include('accountapp.urls')),
    path('profiles/', include('profileapp.urls')),
    path('articles/', include('articleapp.urls')),
    path('comments/', include('commentapp.urls')),

     # 미디어 사진 출력하기 위한 MEDIA 환경 설정 추가
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  • 메인 app에 comment url주소 추가

 

models.py

from django.contrib.auth.models import User
from django.db import models

# Create your models here.
from articleapp.models import Article


class Comment(models.Model):
    article = models.ForeignKey(Article, on_delete=models.SET_NULL, null=True, related_name='comment')
    writer = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='comment')

    content = models.TextField(null=False)

    created_at = models.DateTimeField(auto_now=True)
  • Comment model 작성
  • article, writer, content, created_at 필드 추가

 

 

마이그레이션

model 생성 후 DB에 반영

python manage.py makemigrations
python manage.py migrate

 

forms.py

from django.forms import ModelForm

from commentapp.models import Comment


class CommentCreationForm(ModelForm):
    class Meta:
        model = Comment
        fields = ['content']
  • ModelForm 상속받아 CommentCreationForm 생성
  • Comment model의 content 필드만 사용

 

urls.py

from django.urls import path

from commentapp.views import CommentCreateView

app_name = 'commentapp'

urlpatterns = [
    path('create/', CommentCreateView.as_view(), name='create'),
]
  • comment의 create url 추가
  • CommentCreateView연결

 

views.py

from django.shortcuts import render

# Create your views here.
from django.urls import reverse
from django.views.generic import CreateView

from articleapp.models import Article
from commentapp.forms import CommentCreationForm
from commentapp.models import Comment


class CommentCreateView(CreateView):
    model = Comment
    form_class = CommentCreationForm
    template_name = 'commentapp/create.html'

    def form_valid(self, form):
        temp_comment = form.save(commit=False)
        temp_comment.article = Article.objects.get(pk=self.request.POST['article_pk'])
        temp_comment.writer = self.request.user
        temp_comment.save()
        return super().form_valid(form)

    def get_success_url(self):
        return reverse('articleapp:detail', kwargs={'pk': self.object.article.pk})
  • 댓글 createview 생성
  • create.html의 form에서 hidden으로 보낸 input값인 article_pk가져와서 현재 article 번호 저장
  • 작성자는 request된 user로 저장
  • 댓글 작성후 성공시 작성한 detail페이지로 다시 돌아옴

 

 

create.html

{% load bootstrap4 %}

{% block content %}

<div style="text-align:center;  max-width: 500px; margin: 4rem auto">
    <div class="mb-4">
        <h4>Comment Create</h4>
    </div>
    <form action="{% url 'commentapp:create' %}"  method="post">
        {% csrf_token %}
        {% bootstrap_form form %}

        {% if user.is_authenticated %}
        <input type="submit" class="btn btn-dark rounded-pill col-6 mt-3">
        {% else %}
        <a href="{% url 'accountapp:login' %}?next={{ request.path }}" class="btn btn-dark rounded-pill col-6 mt-3">
            Login
        </a>
        {% endif %}
        <input type="hidden" name="article_pk" value="{{ article.pk }}">
    </form>
</div>


{% endblock %}
  • 댓글 작성 form html 생성
  • user로그인 시 제출 버튼 보이고, 로그아웃 시 로그인 링크로 연결
  • input hidden값으로 article.pk 값 form 전달

 

 

articleapp/views.py

class ArticleDetailView(DetailView, FormMixin):
    model = Article
    form_class = CommentCreationForm
    context_object_name = 'target_article'
    template_name = 'articleapp/detail.html'
  • aritcle detail 뷰에서 장고 제공 mixin form 다중 상속
  • 댓글 form인 CommentCreationForm 추가
* Mixin : 장고가 제공하는 다중 상속

 

 

articleapp/detail.html

{% extends 'base.html' %}
{% load bootstrap4 %}

{% block content %}

<div>
    <div style="text-align: center; max-width: 700px; margin: 4rem auto;">
        <h1>{{ target_article.title }}</h1>
        <h5>{{ target_article.writer.profile.nickname }} </h5>
        <hr>

        <img style="width: 100%; border-radius: 1rem; margin: 2rem 0;" src="{{ target_article.image.url }}" alt="">

        <p>
            {{ target_article.content }}
        </p>

        {% if target_article.writer == user %}
        <a href="{% url 'articleapp:update' pk=target_article.pk %}"
        class="btn btn-primary rounded-pill col-3">
            Update
        </a>

         <a href="{% url 'articleapp:delete' pk=target_article.pk %}"
         class="btn btn-danger rounded-pill col-3">
            Delete
        </a>
        {% endif %}
        <hr>

        {% include 'commentapp/create.html' with article=target_article %}

       
    </div>

</div>

{% endblock %}
  • 댓글 작성하는 create.html include 및 target_article 같이 넘겨줌

 

 

  • 댓글 create 뷰 페이지

 

 

반응형