Я создал таблицу 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})
Может кто-нибудь помочь мне решить этот финалвопрос?