简体   繁体   English

我想使用 Ajax 在 Django 中发送消息

[英]I want to use Ajax to send message in Django

I want to post comment using ajax in Django.我想在 Django 中使用 ajax 发表评论。

I have Message Class related to Post class, and I using PostDetailView to show content of the post and coments.我有与 Post 类相关的 Message Class,并且我使用 PostDetailView 来显示帖子和评论的内容。

I'm getting error Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user\\/(?P<username>[^/]+)\\Z']我收到错误Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user\\/(?P<username>[^/]+)\\Z'] Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user\\/(?P<username>[^/]+)\\Z']

Also I have highlighted at link for bootstrap.我还在引导链接中突出显示。

I tried to delete these two corresponding parts, but I still getting the same error.我试图删除这两个相应的部分,但我仍然得到同样的错误。

this is my code这是我的代码

urls.py网址.py

urlpatterns = [
 path('',PostListView.as_view(),name='blog-home'),
 path('user/<str:username>',UserPostListView.as_view(),name='user-posts'),
 path('post/<int:pk>',PostDetailView.as_view(),name='post-detail'), 
]

views.py视图.py

class PostDetailView(DetailView):
    model = Post
        
    def get(self, *args, **kwargs):
        form = CommentForm()
        comments = Message.objects.all()
        return render(self.request, 'blog/post_detail.html', 
            {"form": form, "comments": comments})

    
    def post(self, *args, **kwargs):
        if self.request.is_ajax and self.request.method == "POST":
            form = CommentForm(self.request.POST)
            if form.is_valid():
                instance = form.save()
                ser_instance = serializers.serialize('json', [ instance, ])
                
                return JsonResponse({"instance": ser_instance}, status=200)
            else:
                return JsonResponse({"error": form.errors}, status=400)

        return JsonResponse({"error": ""}, status=400)

html(where is link to 'user-posts') html(“用户帖子”的链接在哪里)

<div class="post-header">
  <h2 class="post-title">{{object.title}}</h2>
</div>
<div class="author-detail">
  <a
    href="{% url 'user-posts' object.author.username %}"
    class="roomListRoom__author"
  >
    <div class="avatar avatar--small">
      <img src="{{object.author.profile.image.url}}" />
    </div>
    <span>@{{object.author.username}}</span>
  </a>
  <img
    class="rounded-circle account-img"
    src="{{object.author.profile.image.url}}"
  />
  <div class="author-info">
    <p>
      @<a href="{% url 'user-posts' object.author.username %}">
        {{object.author}}
      </a>
    </p>
    <p>{{object.date_posted|timesince|split_timesince:"," }}前</p>
  </div>
</div>

script.js脚本.js

$(document).ready(function () {
  $("#comment-form").submit(function (e) {
    e.preventDefault();
    var serializedData = $(this).serialize();

    $('[name="csrfmiddlewaretoken"]').attr("value");

    $.ajax({
      type: "POST",
      url: $(this).attr("action"),//here will be '{% url ;post-detail object.id %}'
      data: serializedData,
      beforeSend: function (response) {
        $(".save-comment").addClass("disabled").text("saving...");
        console.log(_comment);
      },
      success: function (response) {
        $("#friend-form").trigger("reset");

        var instance = JSON.parse(response["instance"]);
        var fields = instance[0]["fields"];

        $("#comments").prepend(
          `<div class="comment">
            <div class="avatar avatar--small">
              <img
                src="{{message.user.profile.image.url}}"
                alt="user profile image"
              />
            </div>
            <div class="comment-body">
              <span class="comment-author">}</span>
              <span>${fields["body"]}}</span>
            </div>
          </div>`
        );
        // $(".save-comment").removeClass("disabled").text("Submit");
      },
      error: function (response) {
        alert(response["responseJSON"]["error"]);
      },
    });
  });
});

All my code 我所有的代码

How can I fix this?我怎样才能解决这个问题?

"{% url  'user-posts'' username=username|safe %}"

请记住,如果您想在您的 url 中使用用户名,您只需将视图中的用户名作为 args 并使用 django 模板语言将其发送到您的模板

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我希望机器人只发送第一条消息 - I want bot to send first message only 我想在按下发送按钮时显示消息。 并希望重置消息表单 - I want to display the message when I push send button. And want be reset message form 我想在node.js中发送没有Enterkey的消息 - i want to send message without Enterkey in node.js 当我想使用Ajax通过node.js发送/接收请求时,如何在xmlhttp.open()中设置参数“ url” - How to set the argument “url” in xmlhttp.open() when I want to use Ajax to send/receive request with node.js 我想将字符串转换为json字符串并通过ajax发送 - i want to convert string to json string and send it via ajax 我想使用ajax或任何其他方法将图像发送到数据库 - I want to send Image to database using ajax or any other method 我只想使用 ajax 将 textarea 条目作为帖子发送 - I just want to send textarea entry as a post using ajax 我想在不使用 AJAX 和 Django 刷新页面的情况下将产品添加到购物车中 - I want to add product in cart without refreshing page with AJAX and Django 我希望我的机器人仅在用户直接发送消息时向用户发送直接消息 - I want my bot to send direct message to a user ONLY if the user's direct message 想要使用JavaScript和Ajax使用curl将其发送到php脚本以连接到远程服务器 - want to use JavaScript and Ajax to send to a php script using curl to connect to a remote server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM