[英]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"]);
},
});
});
});
How can I fix this?我怎样才能解决这个问题?
"{% url 'user-posts'' username=username|safe %}"
请记住,如果您想在您的 url 中使用用户名,您只需将视图中的用户名作为 args 并使用 django 模板语言将其发送到您的模板
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.