Django - 编辑 HTML 表行并更新数据库

Oum*_*b10 2 html python django ajax post

我创建了一个 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>
Run Code Online (Sandbox Code Playgroud)

这是我的视图,我知道它不应该看起来像这样,因为视图和 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})
Run Code Online (Sandbox Code Playgroud)

更新

我使用了@xxbinxx提供的解决方案,但是在视图函数中,即使在ajax函数中,条件request.method ==“POST”似乎也没有得到验证?

这是更新的代码:

<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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

视图.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})
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决这最后一个问题吗?

xxb*_*nxx 5

是的,您必须使用它AJAX来实现就地编辑。我正在发布快速代码,以便您了解

\n\n
\n

注意:下面的代码有错误;)我不想详细写,因为这对你没有好处。你必须集思广益并亲自尝试。

\n
\n\n
    \n
  • contenteditable=\xe2\x80\x9dtrue\xe2\x80\x9d是使列可编辑。
  • \n
  • 一个属性data-old_value,用于在发出 Ajax 请求更新数据库表中更改的值之前检查旧值。
  • \n
  • 代码正在利用函数saveQuestionAnswer()
  • \n
  • 在模糊事件上更新更改的值和函数highlightEdit()以在编辑模式下突出显示列。
  • \n
\n\n
    <table style="width:100%">\n      <tr>\n        <th>Questions</th>\n        <th>Answers</th>\n        <th>Action</th>\n      </tr>\n      {% for q in questions%}\n      <tr>\n        <td contenteditable=\'true\' data-id="question-{{q.id}}" data-old_value=\'{{q.question}}\' onClick="highlightEdit(this);">{{q.question}}</td>\n        <td contenteditable=\'true\' data-id="answer-{{q.id}}" data-old_value=\'{{q.answer}}\' onClick="highlightEdit(this);">{{q.answer}}</td>\n        <td>\n          <center><a onclick="saveQuestionAnswer(\'{{q.id}}\')">Save your edit --- </a><a href="{% url \'delete_question\' q.id %}">Delete</a></center>\n        </td>\n      </tr>\n      {%endfor%}\n    </table>\n\n    <script>\n    function saveQuestionAnswer(id) {\n\n        editableQuestion = $(\'a[data-id=question-\'+id+\']\') //this will get data-id=question-1 where 1 is the question ID\n        editableAnswer = $(\'a[data-id=answer-\'+id+\']\') //this will get data-id=answer-1 where 1 is the question ID\n\n        // no change change made then return false\n        if ($(editableQuestion).attr(\'data-old_value\') === editableQuestion.innerHTML && $(editableAnswer).attr(\'data-old_value\') === editableAnswer.innerHTML)\n            return false;\n\n        // send ajax to update value\n        $(editableObj).css("background", "#FFF url(loader.gif) no-repeat right");\n        $.ajax({\n            url: "/my-save-url/",\n            type: "POST",\n            dataType: "json",\n            data: {"question": editableQuestion.innerHTML, "answer": editableAnswer.innerHTML}\n            success: function(response) {\n                // set updated value as old value\n                $(editableQuestion).attr(\'data-old_value\', response.question);\n                $(editableQuestion).css("background", "#FDFDFD");\n\n                $(editableAnswer).attr(\'data-old_value\', response.answer);\n                $(editableAnswer).css("background", "#FDFDFD");\n            },\n            error: function() {\n                console.log("errr");\n                alert("An error occurred")\n            }\n        });\n    }\n\n    function highlightEdit(elem){\n      $(elem).css("background", "#e3e3e3") //just add any css or anything, it\'s only to depict that this area is being edited...\n    }\n    </script>\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

您的视图现在将获取 json 格式的数据,如下所示{\'question\': <value>, \'answer\': <value>}

\n\n

如果需要,您可以\'id\'在其中添加另一个键,或者您可以像这样保留您的网址。这里你有你的in url 本身。json/saveQuestionAnswer/<id>id

\n\n

我希望你现在明白了。

\n\n

谢谢

\n