1

Я пытаюсь выполнить ответы на мои комментарии и не уверен, как работает сама ForeignKey. Вот моя модель Comment.Самостоятельная ссылка ForeignKey с комментариями/комментариями ответа

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) 

Сейчас это как мой первоначальный комментарий (родительский комментарий) вид выглядит следующим образом:

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

так, что просто создает регулярный экземпляр Comment. Теперь вот моя попытка ответного комментария (индивидуальный вид):

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

является reply=parent правильный способ создать объект ответа Comment? Я борюсь с тем, как соединить эти два. Мой шаблон, который только делает родитель комментарии выглядит следующим образом:

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

Поэтому, как только я подключить родительский комментарий и ответ комментарий, как бы это сделать в приведенном выше шаблоне?

+0

Возможно, это может быть полезно? http://stackoverflow.com/q/4725343/2750819 – kshikama

+1

Вместо 'parent_id = models.IntegerField (по умолчанию = 0)' он должен быть 'parent = models.ForeignKey (« self », blank = True, null = True) '. –

ответ

0

удалить reply поле просто добавить родительское поле, как показано ниже.

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

Добавление комментариев:

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) 
Смежные вопросы