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

时间:2019-05-24 10:21:45

标签: python html ajax django 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>

这是我的视图,我知道它不应该像这样,因为在视图和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提供的解决方案,但是在视图函数中,条件请求.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})

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

1 个答案:

答案 0 :(得分:2)

是的,您必须使用AJAX来完成就地编辑。我正在发布快速代码,以便您获取想法

  

注意:下面的代码有错误;)我不想写详细信息,因为这对您不利。您必须集思广益,自己动手尝试。

  • contenteditable=”true”用于使列可编辑。
  • 一个属性data-old_value,用于在发出Ajax请求更新数据库表中已更改的值之前检查旧值。
  • 代码正在使用函数saveQuestionAnswer()
  • 在模糊事件中更新更改的值,并使用功能highlightEdit()在编辑模式下突出显示列。
    <table style="width:100%">
      <tr>
        <th>Questions</th>
        <th>Answers</th>
        <th>Action</th>
      </tr>
      {% for q in questions%}
      <tr>
        <td contenteditable='true' data-id="question-{{q.id}}" data-old_value='{{q.question}}' onClick="highlightEdit(this);">{{q.question}}</td>
        <td contenteditable='true' data-id="answer-{{q.id}}" data-old_value='{{q.answer}}' onClick="highlightEdit(this);">{{q.answer}}</td>
        <td>
          <center><a onclick="saveQuestionAnswer('{{q.id}}')">Save your edit --- </a><a href="{% url 'delete_question' q.id %}">Delete</a></center>
        </td>
      </tr>
      {%endfor%}
    </table>

    <script>
    function saveQuestionAnswer(id) {

        editableQuestion = $('a[data-id=question-'+id+']') //this will get data-id=question-1 where 1 is the question ID
        editableAnswer = $('a[data-id=answer-'+id+']') //this will get data-id=answer-1 where 1 is the question ID

        // no change change made then return false
        if ($(editableQuestion).attr('data-old_value') === editableQuestion.innerHTML && $(editableAnswer).attr('data-old_value') === editableAnswer.innerHTML)
            return false;

        // send ajax to update value
        $(editableObj).css("background", "#FFF url(loader.gif) no-repeat right");
        $.ajax({
            url: "/my-save-url/",
            type: "POST",
            dataType: "json",
            data: {"question": editableQuestion.innerHTML, "answer": editableAnswer.innerHTML}
            success: function(response) {
                // set updated value as old value
                $(editableQuestion).attr('data-old_value', response.question);
                $(editableQuestion).css("background", "#FDFDFD");

                $(editableAnswer).attr('data-old_value', response.answer);
                $(editableAnswer).css("background", "#FDFDFD");
            },
            error: function() {
                console.log("errr");
                alert("An error occurred")
            }
        });
    }

    function highlightEdit(elem){
      $(elem).css("background", "#e3e3e3") //just add any css or anything, it's only to depict that this area is being edited...
    }
    </script>

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

您可以根据需要在此'id'中添加另一个密钥json,也可以像这样/saveQuestionAnswer/<id>那样保留您的网址。在这里,您自己的网址中就有id

希望您现在明白了。

谢谢