흰 스타렉스에서 내가 내리지

댓글 본문

Django

댓글

주씨. 2022. 6. 8. 17:00
728x90

models.py

class Blog(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    photo = models.FileField(default="", blank=True, null=True, upload_to='blog_photo')
    date = models.DateTimeField(auto_now_add=True)
    
    
    def __str__(self):
        return self.title
    
    
class Comment(models.Model):
    comment = models.TextField(max_length=200)
    date = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey(Blog, on_delete=models.CASCADE)
    
    def __str__(self):
        return self.comment

 

 

forms.py 에 CommentForm 추가

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['comment']

 

 

 

views.py 에 detail 함수에 comment_form 추가

def detail(request, post_id):
    blog_detail = get_object_or_404(Blog, pk=post_id)
    
    comment_form = CommentForm()
    return render(request, 'detail.html', {'blog_detail':blog_detail, 'comment_form': comment_form})

 

 

 

detail.html 추가

<h1>제목</h1>
{{ blog_detail.title }}

<h2>날짜</h2>
{{ blog_detail.date }}

<h3>본문</h3>
{{ blog_detail.body }}

{% if blog_detail.photo %}
  <img src="{{ blog_detail.photo.url }}" alt="">
{% endif %}

<h3>댓글</h3>
<form action="{% url 'create_comment' blog_detail.id %}" method="POST">
  {% csrf_token %}
  {{ comment_form }}
  <input type="submit">
</form>

 

 

 

urls.py

path('create_comment/<int:post_id>', views.create_comment, name='create_comment'),

 

 

 

views.py

def create_comment(request, post_id):
    if request.method == 'GET':
        pass
    elif request.method == 'POST':
        filled_form = CommentForm(request.POST)
        if filled_form.is_valid():
            finished_form = filled_form.save(commit=False) # 아직은 저장하지 말고 대기하고 있어라
            finished_form.post = get_object_or_404(Blog, pk=post_id)
            finished_form.save()
            
    return redirect('detail', post_id)

 

 

detail.html

{% for comment in blog_detail.comment_set.all %}
  <p>{{ comment }}</p>
  <hr>
{% endfor %}

 

'Django' 카테고리의 다른 글

pagination  (0) 2022.06.09
회원가입, 로그인, 로그아웃  (0) 2022.06.08
사용자가 media 를 업로드 할 수 있도록  (0) 2022.06.08
게시글 detail 페이지 구현  (0) 2022.06.08
DB에 담긴 데이터들을 html에 띄워보자  (0) 2022.06.07