Zorgan Zorgan - 4 years ago 61
Python Question

Self reference ForeignKey with comment/comment reply relationship

I'm trying to implement replies to my comments and am not sure how self ForeignKey's work. Here's my

Comment
model.

class Comment(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
destination = models.CharField(default='1', max_length=12, blank=True)
parent_id = models.IntegerField(default=0)
reply = models.ForeignKey('self', blank=True, null=True)
comment_text = models.TextField(max_length=350, blank=True, null=True)

def __str__(self):
return str(self.comment_text)


Right now this is how my initial comment (parent comment) view looks like:

def user_comment(request):
if request.is_ajax():
comment = CommentForm(request.POST or None)
ajax_comment = request.POST.get('text')
id = request.POST.get('id')

if comment.is_valid():
comment = Comment.objects.create(comment_text=ajax_comment, destination=id, user=request.user)
comment.save()
username = str(request.user)
return JsonResponse({'text': ajax_comment, 'username': username, 'id': comment.id})


so that just creates a regular instance of
Comment
. Now here's my attempt at a reply comment (seperate view):

def comment_reply(request):
if request.is_ajax():
comment = CommentForm(request.POST or None)
reply_text = request.POST.get('reply_text')
id = request.POST.get('id')
parent_id = request.POST.get('parent_id')
parent = Comment.objects.get(id=parent_id)

if comment.is_valid():
comment = Comment.objects.create(comment_text=reply_text, destination=id,
user=request.user, parent_id=parent_id, reply=parent)
comment.save()
username = str(request.user)
return JsonResponse({'reply_text': reply_text, 'username': username})


is
reply=parent
the right way to create the reply
Comment
object? I'm struggling with how to connect the two. My template, which just renders parent comments looks like this:

{% for i in comment_list %}
<div class='comment_div' data-comment_id="{{ i.id }}">
<div class="left_comment_div">
<div class="username_and_votes">
<h3><a class='username_foreign'>{{ i.user }}</a></h3>
</div>
<br>
<p>{{ i.comment_text }}</p>
</div>
<a class="reply">reply</a><a class="cancel_comment">cancel</a>
<span><a class="comment_delete" data-comment_id="{{ i.id }}">x</a></span>
</div>
{% endfor %}


So once I connect the parent comment and reply comment, how would it render in the template above?

Answer Source

remove reply field just add parent field like below.

parent = models.ForeignKey("self", blank=True, null=True, related_name="comment_parent")

Adding comments:

if request.POST.get('parent_id'):
     parent = Comment.objects.get(id=request.POST.get('parent_id'))
     comment = Comment.objects.create(comment_text=reply_text, destination=id, user=request.user, parent=parent)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download