【问题标题】:How to send a template variable in loop in html to javascript?如何将html循环中的模板变量发送到javascript?
【发布时间】:2019-07-13 10:28:56
【问题描述】:

我在 html 中有一个模型的 Post 类变量,我想添加将 cmets 添加到任何帖子的能力。所以我有一个用于单击按钮添加评论的 js 函数,我想发送那个用户想要为其添加评论的 post_id,但由于这个标签处于循环中,它总是发送相同的 post_id !!! 我该怎么办??

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!!!');
        }
    });
}

视图:

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)

型号:

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

【问题讨论】:

  • 您的标记是错误的(或者,更准确地说,它是无效的):标签的“id”属性必须是唯一的。这实际上就是拥有它们的全部意义......

标签: javascript html django django-templates


【解决方案1】:

尝试将帖子 pk 放入输入 id 并作为按钮功能参数:

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

然后就可以在 GET 请求中发送具体的内容了:

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!!!');
    }
});
}

【讨论】:

  • 这是一个非常好的主意:) .... 但是我收到一个错误:/user_add_comment save() 处的 ValueError 被禁止以防止由于未保存的相关对象“profile_user”而导致数据丢失。
猜你喜欢
  • 2018-01-04
  • 1970-01-01
  • 1970-01-01
  • 2011-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多