【问题标题】:Django - edit HTML table rows and update databaseDjango - 编辑 HTML 表格行并更新数据库
【发布时间】: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: 中的 datasuccess 之间缺少逗号“,”

标签: python html ajax django post


【解决方案1】:

是的,您必须使用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>

您的视图现在将获取 json 格式的数据,如 {'question': &lt;value&gt;, 'answer': &lt;value&gt;}

您可以根据需要在此json 中添加另一个密钥'id',或者您可以保留您的网址,如/saveQuestionAnswer/&lt;id&gt;。在这里你有你的id 网址本身。

希望你现在明白了。

谢谢

【讨论】:

  • @Oumab10 有帮助吗?你还在找什么?
  • 我的视图功能有问题,它似乎没有得到编辑后的行,而且我不知道要修复什么,我想弄清楚...
  • JS部分你看懂了吗?
  • 全局是的,我明白了(我从未使用过 Javascript,我是网络编程新手)
  • 好的,你做得很好。试着使用我上面给你的代码。在您看来,您将在request.POST 中获得 JSON 数据。试试吧,如果您有任何问题,请告诉我们,但首先要自己努力。
猜你喜欢
  • 1970-01-01
  • 2017-08-01
  • 1970-01-01
  • 2018-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-02
相关资源
最近更新 更多