[英]Django ModelForm creating new instance instead of updating existing database entry
[英]Django: update creating new object instead of updating existing in django?
我正在使用 django 和 ajax 創建評論更新 function,並且我正在嘗試在不刷新頁面的情況下更新評論,現在當我點擊編輯框以進行編輯時,我正在編輯之前文本(評論)而不是將新編輯保存到舊編輯; 它繼續創建一個新的評論,我該如何防止它。
視圖.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)
ajax代碼
// 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
}
索引.html
<button data-cid="{{ c.id }}" class="btn-edit">Edit</button>
什么可能是最好的解決方法?
我假設您發布到ajaxComment
是新的還是編輯的。 如果它是一個編輯,只需傳遞一個帶有評論 PK 的額外 POST:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.