Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
108 views

How To Make Add Replies To Comments in Django?: 3 Answers

Uploaded by

Bleep News
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views

How To Make Add Replies To Comments in Django?: 3 Answers

Uploaded by

Bleep News
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

About Products For Teams Search… Log in Sign up

Home
How to make add replies to comments in Django? Ask Question

PUBLIC Asked 4 years, 5 months ago Active 8 months ago Viewed 11k times

Questions
I'm making my own blog with Django and I already made a Comments system.. I want to add the
Tags The Overflow Blog
replies for each comment (like a normal comment's box) and I don't know what to do this is my
Users 5 current models.py comments: Podcast 395: Who is building clouds for
the independent developer?
COLLECTIVES
class Comment(models.Model): Exploding turkeys and how not to thaw
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') your frozen bird: Top turkey questions...
Explore Collectives
author = models.ForeignKey(User, on_delete=models.CASCADE)
6
text = models.TextField()
FIND A JOB
created_date = models.DateField(auto_now_add=True) Featured on Meta

Jobs parent = models.ForeignKey('self', null=True, related_name='replies')


Now live: A fully responsive profile
Companies def __str__(self):
return self.text Reducing the weight of our footer

TEAMS Two B or not two B - Farewell, BoltClock


and this is the .html where I use the comments and Bhargav!
Stack Overflow for
Teams – Collaborate
and share knowledge {% for comment in post.comments.all %}
with a private group. <ul>
{{ comment.text }}
{% for reply in comment.replies.all %}
<li>
{{ reply.text }}
</li>
{% endfor %}
<ul>
{% endfor %}
Create a free Team

What is Teams?
and apparently It is working but when I try to make a comment in the admin site of Django it forces
Your privacy me to put a "Parent" to each comment (and this is not obligatory beacuse not every comment is a
By clicking “Accept all cookies”, you agree Stack Exchange can reply) I also don't know how to add the reply "button" in the HTML file. Please help tell me what Report this ad
store cookies on your device and disclose information in
accordance with our Cookie Policy. changes can I do to make a simple comment box with replies . Thanks a lot
Remote jobs
Accept all cookies python html django comments
Full Stack Developer (Django +
React)
Customize settings Share Improve this question Follow edited Jun 30 '17 at 7:03 asked Jun 30 '17 at 2:33 Self Decode No office location
badiya Deivbid $30K - $70K REMOTE
2,158 11 23 363 2 5 13 django python

Senior Python Developer - Django


I can recommend this tool : disqus.com – DavidS Jun 30 '17 at 6:49 Rest Framework
n.exchange Lisbon, Portugal
Add a comment €70K - €100K REMOTE RELOCATION

ethereum bitcoin

3 Answers Active Oldest Votes


Software Architect (Django/Flask +
React)
Self Decode No office location
I had the same problem and resolved it as follows:
$60K - $100K REMOTE

python django
10 1. For admin site as mentioned above just set blank=True for parent field. My comment model:

Python Developer (Remote)


class Comment(models.Model):
X-Team No office location
post = models.ForeignKey(Post, related_name='comments')
REMOTE
name = models.CharField(max_length=80)
email = models.EmailField(max_length=200, blank=True) python django
body = models.TextField()
created = models.DateTimeField(auto_now_add=True) Engineering Manager
updated = models.DateTimeField(auto_now=True) Self Decode No office location
# manually deactivate inappropriate comments from admin site $50K - $100K REMOTE
active = models.BooleanField(default=True)
parent = models.ForeignKey('self', null=True, blank=True, related_name='replies') python reactjs

class Meta: Back-end developer (Python)


# sort comments in chronological order by default Nolk Montreal, QC, Canada
ordering = ('created',) REMOTE

python elasticsearch
def __str__(self):
return 'Comment by {}'.format(self.name)
(Senior) Frontend Engineer at
sustainable start-up (m/f/x) -
Munich or Remote
remember to run makemigrations and migrate
FINN München, Germany
€60K - €80K REMOTE RELOCATION
2.Let's start with views. I'm using the post_detail view to display the post and its comments. We
javascript reactjs
add a QuerySet to retrieve all parent active comments for this post. After this, we validate the
submitted data using the form's is_valid() . If the form is valid we check if submitted data comes
Senior WordPress Developer
from hidden input in replay button form. Next if parent_id exits we create parent Curotec No office location
object( parent_obj ) for replay comment and replay_comment object, then we assign parent_obj to REMOTE
replay_comment . If parent_obj is equal to None we just proceed with normal comment by creating html wordpress
new_comment object and saving it to the database.

View more jobs on Stack Overflow


def post_detail(request, post):
# get post object
post = get_object_or_404(Post, slug=post)
# list of active parent comments
28 people chatting
comments = post.comments.filter(active=True, parent__isnull=True)
if request.method == 'POST': Python
# comment has been added 12 mins ago - Jon Clements
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
parent_obj = None
# get parent comment id from hidden input Meta Stack Overflow Comment Archive
try: 14 mins ago - Boson
# id integer e.g. 15
parent_id = int(request.POST.get('parent_id'))
except:
parent_id = None
# if parent_id has been submitted get parent_obj id Linked
if parent_id:
parent_obj = Comment.objects.get(id=parent_id)
0 After posting content of my blog ni, they
# if parent object exist
are shown in html format rather than pure
if parent_obj:
text
# create replay comment object
replay_comment = comment_form.save(commit=False)
# assign parent_obj to replay comment Related
replay_comment.parent = parent_obj
# normal comment 6016 How do I merge two dictionaries in a single
# create comment object but do not save to database expression (take union of dictionaries)?
new_comment = comment_form.save(commit=False)
# assign ship to the comment 6430 How do I check whether a file exists without
new_comment.post = post exceptions?
# save
new_comment.save() 4738 How to horizontally center an element
return HttpResponseRedirect(post.get_absolute_url())
else: 8643 Can comments be used in JSON?
comment form = CommentForm()
2973 How to make function decorators and chain
Simple comment form: them together?

4358 How to make a flat list out of a list of lists


class CommentForm(forms.ModelForm):
class Meta: 3192 How can I add new keys to a dictionary?
model = Comment
fields = ('name', 'email', 'body') 1482 How do you do block comments in YAML?

1745 Comments in Markdown


* More about ModelForm
1295 Is there a way to create multiline comments
in Python?
And lastly template. We need to create two forms. One form for comments and the second one for
replays. Here you have simple template:
Hot Network Questions
<!-- Comments Form --> Why wouldn't tribal chiefs use berserkers in
<h2>Add a new comment</h2> warfare?
<form action="." method="post">
How to manipulate the colours when joining
{{ comment_form.as_p }} points in ListPlot
{% csrf_token %}
<button type="submit">Add comment</button> When and why did English stop pronouncing
</form> ‘hour’ with an [h] like its spelling still shows?

How to select and delete a column of text in


<!-- Comment with nested comments --> emacs?
{% for comment in comments %}
How to compensate noise at the output of logic
<div class="comment" style="background-color: powderblue">
gates?
<p class="info">{{ comment.name }} | {{ comment.created }}</p>
{{ comment.body|linebreaks }} Do I need to list any references for common
knowledge?
{% for replay in comment.replies.all %} "Mama" is now a trademark word. Can't use this
<p class="info">{{ replay.name }} | {{ replay.created }}</p> word any more?
<li>{{ replay.body }}</li>
What's going on in this musical notation?
{% endfor %}
Why is 有 used in 我最喜欢的科目有艺术,中文和
<h5>Replay</h5> 化学?
<form action="." method="post">
Freezing blue cheese
{{ comment_form.as_p }}
{% csrf_token %} What (paint)care can I provide to a brand new car
<!-- Hidden input for parent comment.id --> before driving off the dealership?
<input type="hidden" name="parent_id" value="{{ comment.id }}">
Why are legal decisions in the US so politicized?
<input class="btn btn-primary" type="submit" value="Replay">
</form> Is it possible to get a reliable match from
</div> 'microscopic hair analysis'?
{% empty %}
Single word for one who enjoys something?
<h4>There are no comments yet.</h4>
{% endfor %} How constrain 2d slider in Manipulate to a
specified region?

Why is there only one variable displayed in the


just add some nice css and maybe jquery to have fade in reply comments and that's all. Inspector?

How many images of Didymos could be


Share Improve this answer Follow answered Oct 28 '17 at 17:58 transmitted by Dart between the first full size
image and the impact?
casol
434 1 6 11 Minimum number of runways required for
international airports?

what's the role of parent model field can you please explain. – Lord-shiv Jun 22 at 14:43 Is a USB security key trackable among websites?

Effects of mRNA vaccines on human body


Add a comment processes

Does "четверть" have a meaning in school topics


equivalent to term, rather than quarter

first Question:parent must be set in admin. Cartesian literal notation

How can I fit a glass cooktop hood into a space


3 parent = models.ForeignKey('self', null=True, blank=True, related_name='replies') that's too tight?

A gross of colored dots

blank=True can let you don't set parent in admin.


Question feed

second Question:add comment dynamicly.

<form id="comment-form" method="post" role="form">


{% csrf_token %}
<textarea id="comment" name="comment" class="form-control" rows="4" placeholder="input
<button type="submit" class="btn btn-raised btn-primary pull-right">submit</button>
</form>

$('#comment-form').submit(function(){
$.ajax({
type:"POST",
url:"{% url 'article_comments' article.en_title %}",
data:{"comment":$("#comment").val()},
beforeSend:function(xhr){
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
},
success:function(data,textStatus){
$("#comment").val("");
$(".comment ul").prepend(data);
},
error:function(XMLHttpRequest, textStatus, errorThrown){
alert(XMLHttpRequest.responseText);

});
return false;
});

view.py:

print_comment = u"<p>comment:{}</p>".format(text)
if parent:
print_comment = u"<div class=\"comment-quote\">\
<p>\
<a>@{}</a>\
{}\
</p>\
</div>".format(
parent.user.username,
parent.text
) + print_comment
# current comment
html = u"<li>\
<div class=\"comment-tx\">\
<img src={} width=\"40\"></img>\
</div>\
<div class=\"comment-content\">\
<a><h1>{}</h1></a>\
{}\
<p>{}</p>\
</div>\
</li>".format(
img,
comment.user.username,
print_comment,
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
)

return HttpResponse(html)

Share Improve this answer Follow answered Jun 30 '17 at 2:49


Ykh
6,841 1 16 29

Hi, thank you for your answe, but there's no way to make this replies without ajax or another framework? I
think that I'm getting complicated and the task is easy just add replies to comments :( –  Deivbid Jun 30 '17
at 4:36

Add a comment

models.py

1 class Comment(models.Model):
author = models.CharField(max_length=100)
comment_field = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
post = models.ForeignKey('Post', on_delete=models.CASCADE)
reply = models.ForeignKey('Comment', on_delete=models.CASCADE, related_name="replies",

def __str__(self):
return self.author

views.py

def post_detail(request, slug):


post = Post.objects.get(slug=slug)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
reply_obj = None
try:
reply_id = int(request.POST.get('reply_id'))
except:
reply_id = None
if reply_id:
reply_obj = Comment.objects.get(id=reply_id)

author = form.cleaned_data['author']
comment = form.cleaned_data['comment']
if reply_obj:
Comment(author=author,comment_field=comment, reply=reply_obj, post=post).sav
else:
Comment(author=author,comment_field=comment, post=post).save()
return redirect(reverse('post_detail', args=[post.slug]))
else:
form = CommentForm()
comments = Comment.objects.filter(post=post, reply=None).order_by('-date_created')
context = {
'post':post,
'form':form,
'comments':comments
}
return render(request, 'post_detail.html', context)

template (post_detail.html)

{% for comment in comments %}


{{comment.author}}
{{comment.date_created.date}}
{{comment.comment_field}}

{% for reply in comment.replies.all %}


{{reply.author}}
{{reply.date_created.date}}
{{reply.comment_field}}
{% endfor %}
<a class="text-decoration-none" data-bs-toggle="collapse" href="#collapseExample{{c
Reply </a>
<div class="collapse" id="collapseExample{{comment.id}}">
<div>
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
{{ form.author }}
</div>
<div class="form-group mt-md-2">
{{form.comment}}
</div>
<input type="hidden" name="reply_id" value="{{ comment.id }}">
<button class="btn btn-primary mt-md-1" type="submit" value="Re
</div>
</div>
<hr>
{% endfor %}

Share Improve this answer Follow answered Mar 16 at 9:46


Akram Narejo
54 1 5

thank you very much this helped a lot. Just wanted to point out that the collapse might not work right away.
But can be easily adjusted or removed. Extremely helpful answer. Thank you! – buchstabe May 15 at 9:46

1 you're welcome. I'm happy that it helped you. – Akram Narejo May 17 at 12:41

Add a comment

Your Answer

Sign up or log in Post as a guest


Name
Sign up using Google

Sign up using Facebook Email


Required, but never shown

Sign up using Email and Password

Post Your Answer By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged python html django

comments or ask your own question.

STACK OVERFLOW PRODUCTS COMPANY STACK EXCHANGE Blog Facebook Twitter LinkedIn Instagram
NETWORK
Questions Teams About
Technology
Jobs Talent Press
Culture & recreation
Developer Jobs Directory Advertising Work Here
Life & arts
Salary Calculator Enterprise Legal
Science
Help Privacy Policy
Professional
Mobile Terms of Service
Business
Disable Responsiveness Contact Us
Cookie Settings
API
Cookie Policy site design / logo © 2021 Stack Exchange Inc; user contributions
Data licensed under cc by-sa. rev 2021.11.25.40831

You might also like