【发布时间】:2021-10-19 21:05:54
【问题描述】:
我正在尝试编辑我网站上的现有帖子(表单),但是当我单击“编辑”时,我在控制台中得到了这个:Fetch finished loading: POST "http://127.0.0.1:8000/edit_post/ 18"。 状态为 201,所以我认为该页面跳过了大部分 javascript 并直接将其发布/保存到服务器。此外,当我单击“编辑”时,应该立即出现一个文本框,其中包含我的帖子文本。但这永远不会打开,它只是说 fetch 在控制台中适当地完成加载。
如何确保首先运行所有 Javascript?我尝试使用 preventDefault 并继续遇到未捕获的类型错误。我对 Javascript 还很陌生,所以我还在学习这个。
例如,我在 event_handeler 函数中尝试的一件事是:
document.querySelectorAll("#textarea").addEventListener("submit", function(event) {
document.querySelector(`#post-edit-${id}`).innerHTML += "Sorry!";
event.preventDefault();
})
但我遇到了未捕获的类型错误。
function edit_handeler(element) {
id = element.getAttribute("data-id");
document.querySelector(`#post-edit-${id}`).style.display = "block";
document.querySelector(`#post-content-${id}`).style.display = "none";
edit_btn = document.querySelector(`#edit-btn-${id}`);
edit_btn.textContent = "Save";
edit_btn.setAttribute("class", "text-success edit");
if (edit_btn.textContent == "Save") {
edit_post(id, document.querySelector(`#post-edit-${id}`).value); //here
edit_btn.textContent = "Edit";
edit_btn.setAttribute("class", "text-primary edit");
}}
function edit_post(id, post) {
const body = document.querySelector(`#post-content-${id}`).value;
fetch(`/edit_post/${id}`, {
method: "POST",
body: JSON.stringify({
body:body
})
}).then((res) => {
document.querySelector(`#post-content-${id}`).textContent = post;
document.querySelector(`#post-content-${id}`).style.display = "block";
document.querySelector(`#post-edit-${id}`).style.display = "none";
document.querySelector(`#post-edit-${id}`).value = post.trim();
});
}
views.py
@csrf_exempt
def edit_post(request, pk): #used to take in pk here also
post = Post.objects.get(id=pk) # was id=pk
form = PostForm(instance=post)
if request.method == "POST":
form = PostForm(request.POST, instance=post)
if form.is_valid():
form.save()
return JsonResponse({}, status=201) # this works to edit and save to db
else:
if request.method == "GET":
form = PostForm(instance=post)
form_for_post = {'form': PostForm()}
return render(request, "network/make_post.html", {
"post": post,
"form_for_post": form,
})
相关的urls.py
path('edit_post/<str:pk>', views.edit_post, name="edit_post"),
相关 html - 第一部分是单击“编辑”时应打开的文本区域。 下一部分是编辑按钮。
span id="post-content-{{i.id}}" class="post">{{i.text}}</span> <br>
<textarea data-id="{{i.id}}" id="post-edit-{{i.id}}"
style="display:none;" class="form-control textarea" row="3">{{i.text}}</textarea>
<button class="btn-btn primary" data-id="{{i.id}}" id="edit-btn-{{i.id}}"
onclick="edit_handeler(this)" >Edit</button>
【问题讨论】:
标签: javascript django django-forms javascript-objects fetch-api