Django: обновление создания нового объекта вместо обновления существующего в django?
я создаю функцию обновления комментария используя django и ajax, и я пытаюсь обновить комментарий без обновления страницы, теперь когда я нажимаю на кнопку edit, существующий комментарий заполняется в поле ввода готовый к редактированию, когда я редактирую текст (комментарий) вместо сохранения новой правки к старой, он идет вперед и создает новый комментарий все вместе, как мне предотвратить это.
view.py
## edit comment
@csrf_exempt
def edit_comment(request):
if request.method == "POST":
id = request.POST.get("cid")
comment = Comment.objects.get(pk=id)
comment_data = {"id": comment.id, "comment": comment.comment, "video": comment.video.id}
return JsonResponse(comment_data)
## Create comment
def ajaxComment(request):
if request.method == "POST":
pk = request.POST.get("id")
video = Video.objects.get(id=pk)
user = request.user
comment = request.POST.get("comment")
new_comment = Comment(user=user, video=video, comment=comment)
new_comment.save()
print(id)
print(user)
print(comment)
print(video)
response = "Comment Posted"
return HttpResponse(response)
код аякса
// Edit
$('.comment-wrapper').on("click", ".btn-edit", function(){
console.log("Edit Button Cliked");
let id = $(this).attr("data-cid");
console.log(id);
mydata = {cid:id}
$.ajax({
url: "{% url 'edit-comment' %}",
method:"POST",
data:mydata,
success: function(data){
console.log(data);
$("#id").val(data.id)
$("#id").val(data.video)
$("#comment").val(data.comment)
// $(".new_comment").val(data.video)
console.log(data.id);
},
})
})
$(document).on("submit", "#comment_form", function(e){
e.preventDefault();
let _comment = $("#comment").val()
console.log("send button clicked")
$.ajax({
type: "POST",
url: "{% url 'save-comment' %}",
data:{
id: $("#id").val(),
comment: _comment,
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function(){
// Some code
}
index.html
<button data-cid="{{ c.id }}" class="btn-edit">Edit</button>
что может быть лучшим решением для этого?
Предполагается, что вы постите в ajaxComment
новый или отредактированный комментарий. Если это правка, просто передайте дополнительный POST с PK комментария:
def ajaxComment(request):
if request.method == "POST":
pk = request.POST.get("id")
video = Video.objects.get(id=pk)
user = request.user
comment = request.POST.get("comment")
if pk:
# is an edit
o = Comment.objects.get(pk=pk)
o.comment = comment
# you could chop these two out
o.video = video
o.user = user
o.save()
response = "Comment Edited"
else:
# is new
new_comment = Comment(user=user, video=video, comment=comment)
new_comment.save()
response = "Comment Created"
print(id)
print(user)
print(comment)
print(video)
return HttpResponse(response)