models.py
Comment
that references
Post
using a ForeignKey.
from django.db import models
class Post(models.Model):
# existing fields like title, content, etc.
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
content = models.TextField()
# other fields like author, timestamp, etc.
python manage.py makemigrations
python manage.py migrate
admin.py
Comment
model to manage it through the
Django admin interface.
from django.contrib import admin
from .models import Comment
admin.site.register(Comment)
forms.py
Comment
model to handle user
submissions.
from django import forms
from .models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['content']
views.py
from django.shortcuts import render, redirect
from .models import Post, Comment
from .forms import CommentForm
def post_detail(request, post_id):
post = Post.objects.get(id=post_id)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail', post_id=post.id)
else:
form = CommentForm()
return render(request, 'post_detail.html', {'post': post, 'form': form})
templates/
<!-- Inside post_detail.html -->
<h1>{{ post.title }}</h1>
<p>{{ post.content }}</p>
<hr>
<h2>Comments</h2>
{% for comment in post.comment_set.all %}
<p>{{ comment.content }}</p>
{% endfor %}
<hr>
<h2>Add a Comment</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>