작정하고 Django (37) - Mixin 소개 및 Commentapp 구현

김의찬·2023년 5월 30일

작정하고 Django !

목록 보기
38/45

CommentApp - 댓글앱

Mixin

CreateView에서는 form이 있지만 DetailView 에서는 없고 object가 존재

DetailView 에서 위에는 content , 밑에는 comment Form이 들어가야함.

이와같이 다중상속 형식으로 구현

commentapp 의 요건

    1. Create / DeleteView
    1. Success_url to related article
    1. Model (article, writer, content, created_at)

commentapp 생성

settings.py

url 등록

url 생성

CommentCreateView 생성

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})

model 생성

form 작성

detail.html 및 create.html 수정 및 작성

{% extends 'base.html' %}


{% 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 %}

{% 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 %}

ArticleDetailView 수정

상속 과정 포함
article 에서 comment를 바로 달 수 있게 함.

comment create 확인

결과 확인

profile
김의찬입니다

0개의 댓글