0

I have a variable of Post class of model in html and i want to add ability of adding comments to any posts. So i have a js function for click of button to add comment and i want to send that post_id which user want to add comment for it but because of this tag is in a loop it always send a same post_id!!! What can i do??

html:

{% extends "base.html" %}
   {% block body_block %}
       <h2>Profile:</h2>
       <h2>Posts:</h2>
       {% for temp_user_posts in user_posts %}
           <div class="profile_page">
               <h3><b>{{ temp_user_posts.post }}</b></h3>
               <p>{{ temp_user_posts.post_time }}</p>

           </div>
               <label for="user-comment">comment:</label>
               <input id="user-comment" type="text" name="{{ temp_user_posts.pk 
   }}">
               <button onclick="add_comment_button();">add comment</button>

       {% endfor %}

   {% endblock %}

js:

function add_comment_button() {
    alert($('#user-comment').attr("name"));
    $.ajax({
        type: "GET",
        url: '/user_add_comment',
        data: {
            "comment_text": $('#user-comment').val(),
            "post_pk": $('#user-comment').attr("name"),
        },
        dataType: "json",
        success: function (data) {
            location.href = data["url"]
        },
        failure: function () {
            alert('There is a problem!!!');
        }
    });
}

view:

def user_add_comment(request):
    post_pk = request.GET.get('post_pk', None)
    post = PostModel.objects.get(pk=post_pk)
    comment = CommentPostModel()
    comment.post = post
    user_info = UserProfileInfo.objects.filter(user=request.user)
    user_info2 = object()
    for temp_user_info in user_info:
        user_info2 = temp_user_info
        break
    comment.profile_user = user_info2
    comment.text = request.GET.get('post_text', None)
    comment.save()
    data = {
        "url":"/profile_page",
    }
    return JsonResponse(data)

model:

class UserProfileInfo(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=100, blank=True, default="Bio")
    profile_pic = models.ImageField(upload_to='profile_users', blank=True)

    def __str__(self):
        return self.user.username


class PostModel(models.Model):
    username = models.CharField(max_length=20, unique=False, verbose_name="Username", default="")
    image = models.ImageField(upload_to='user_images', blank=True)
    post = models.TextField(max_length=100, blank=True)
    post_time = models.DateTimeField(default=datetime.now, blank=True)

    def set_post_time(self):
        self.post_time = datetime.now()
        self.save()

    def __str__(self):
        return self.username
1
  • Your markup is wrong (or, more exactly, it's invalid): the "id" attribute of a tag MUST be unique. That's actually the whole point of having them... Commented Feb 20, 2019 at 13:11

1 Answer 1

1

Try putting the post pk in the input id and as the button function argument:

<input id="user-comment-{{ temp_user_posts.pk }}" type="text" name="{{ temp_user_posts.pk }}">
<button onclick="add_comment_button({{ temp_user_posts.pk }});">add 
comment</button>

Then you'll be able to send the specific content in the GET request:

function add_comment_button(postPk) {
$.ajax({
    type: "GET",
    url: '/user_add_comment',
    data: {
        "comment_text": $('#user-comment-' + postPk).val(),
        "post_pk": postPk,
    },
    dataType: "json",
    success: function (data) {
        location.href = data["url"]
    },
    failure: function () {
        alert('There is a problem!!!');
    }
});
}
Sign up to request clarification or add additional context in comments.

1 Comment

Its very good idea:) .... But i receive an error : ValueError at /user_add_comment save() prohibited to prevent data loss due to unsaved related object 'profile_user'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.