Django-编辑HTML表格行并更新数据库 [英] Django - edit HTML table rows and update database

查看:114
本文介绍了Django-编辑HTML表格行并更新数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个HTML表,其中包含一些信息.但是,我想增加编辑表行文本的可能性,并通过单击保存"来更新数据库.

I created a HTML table, it contains some information. However I want to add the possibility to edit table row text and by clicking "save", the database would be updated.

有人可以帮助我吗?

我需要使用Ajax吗?如果可以,我可以得到一些指导吗?

Do I need to use Ajax? If so please can I get some guidance?

<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表之间没有传递任何参数,需要对此进行修复:

Here is my view, I know it shouldn't look like this because there is no parameter passed between the view and the HTML table, this needs to be fixed:

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函数中也是如此?

I used the solution that @xxbinxx provided, However in the view function, the condition request.method == "POST" doesn't seem to be verified even if it's in ajax function ?

这里是更新的代码:

<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})

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

Can someone help me solve this final issue ?

推荐答案

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

Yes you'll have to use AJAX to achieve in-place editing. I'm posting quick code so you get the idea.

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

NOTE: the below code has errors ;) I don't want to write in detail as it would be of no good to you. You must brainstorm and try it yourself.

  • contenteditable=true用于使列可编辑.
  • 一个属性data-old_value,用于在发出Ajax请求更新数据库表中已更改的值之前检查旧值.
  • 代码正在使用功能saveQuestionAnswer()
  • 在模糊事件中更新更改的值,并使用功能highlightEdit()在编辑模式下突出显示列.
    • contenteditable="true" is to make column editable.
    • an attribute data-old_value to keep old value to check before making Ajax request to update changed value in your database table.
    • Code is making use of function saveQuestionAnswer()
    • on blur event to update changed value and function highlightEdit() to highlight column in edit mode.
    •     <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',也可以像这样/saveQuestionAnswer/<id>那样保留您的网址.在这里,您可以在网址本身中添加id.

      you can add another key 'id' in this json if you want, or you can keep your url like this /saveQuestionAnswer/<id>. Here you have your id in url itself.

      我希望你现在明白了.

      谢谢

      这篇关于Django-编辑HTML表格行并更新数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆