【发布时间】:2019-10-10 22:36:33
【问题描述】:
我创建了一个 HTML 表格,它包含一些信息。但是我想添加编辑表格行文本的可能性,并通过单击“保存”,数据库将被更新。
有人可以帮助我吗?
我需要使用 Ajax 吗?如果是这样,我可以得到一些指导吗?
<table style="width:100%">
<tr>
<th>Questions</th>
<th>Answers</th>
<th>Action</th>
</tr>
{% for q in questions%}
<tr>
<td contenteditable='true'>{{q.question}}</td>
<td contenteditable='true'>{{q.answer}}</td>
<td>
<center><a href="{% url 'edit_question' q.id %}">Save Edit --- </a><a href="{% url 'delete_question' q.id %}">Delete</a></center>
</td>
</tr>
{%endfor%}
</table>
这是我的视图,我知道它不应该是这样的,因为视图和 HTML 表之间没有传递参数,这需要修复:
def edit_question(request,id):
question = Question.objects.get(id=id)
if(question):
question.update(question = quest, answer = ans)
return redirect('list_questions')
return render(request, 'generator/questions.html', {'question': question})
更新
我使用了@xxbinxx 提供的解决方案,但是在视图函数中,条件 request.method == "POST" 似乎没有被验证,即使它在 ajax 函数中?
这是更新的代码:
<script type="text/javascript">
function saveQuestionAnswer(e, id) {
e.preventDefault();
console.log(id)
editableQuestion = $('[data-id=question-' + id + ']')
editableAnswer = $('[data-id=answer-' + id + ']')
console.log(editableQuestion.text(), editableAnswer.text())
$.ajax({
url: "list/update/"+id,
type: "POST",
dataType: "json",
data: { "question": editableQuestion.html(), "answer": editableAnswer.html() },
success: function(response) {
// set updated value as old value
alert("Updated successfully")
},
error: function() {
console.log("errr");
alert("An error occurred")
}
});
return false;
}
</script>
HTML:
<table style="width:90%">
<tr>
<th ><font color="#db0011">Questions</th>
<th><font color="#db0011">Answers</th>
<th><font color="#db0011">Action</th>
</tr>
{% for q in questions%}
<tr>
<td width="40%" height="50px" contenteditable='true' data-id="question-{{q.id}}" data-old_value='{{q.question}}' onClick="highlightEdit(this);">{{q.question}}</td>
<td width="45%" height="50px" contenteditable='true' data-id="answer-{{q.id}}" data-old_value='{{q.answer}}'>{{q.answer}}</td>
<td width="15%" height="50px"><center>
<a class="button" href="{% url 'edit_question' q.id %}" onclick="saveQuestionAnswer('{{q.id}}')">Edit</a>
<a class="button" href="{% url 'delete_question' q.id %}">Delete</a>
</center></td>
</tr>
{%endfor%}
</table>
views.py
def edit_question(request,id):
quest = Question.objects.get(id=id)
print(quest)
if request.method=='POST': # It doesn't access this condition so the updates won't occur
print("*"*100)
quest.question = request.POST.get('question')
quest.answer = request.POST.get('answer')
print(quest)
quest.save()
return redirect('list_questions')
return render(request, 'browse/questions.html', {'quest': quest})
有人可以帮我解决最后一个问题吗?
【问题讨论】:
-
是的,您必须使用
ajax进行就地编辑。让我为您准备一个虚拟 HTML。你会明白的。 -
检查答案。让我知道它是否值得。
-
好的,再次感谢,我马上就做
-
更新问题。代码
data: {"question": editableQuestion.innerHTML, "answer": editableAnswer.innerHTML} success:中的data和success之间缺少逗号“,”
标签: python html ajax django post