Django - edit HTML table rows and update database

2020-08-01 05:35发布

问题:

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.

Can someone help me?

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>

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

UPDATE

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 ?

heres the updated code :

<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 ?

回答1:

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” 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>

Your view will now get data in json format as {'question': <value>, 'answer': <value>}

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.

I hope you understand now.

Thanks