1

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 ?

4
  • yes you'll have to use ajax for in place editing.. Let me prepare an dummy HTML for you. You'll get the idea.
    – xxbinxx
    May 24, 2019 at 10:44
  • Check answer. Let me know if it's worth.
    – xxbinxx
    May 24, 2019 at 11:36
  • Ok thanks again, I'll do that right now
    – Oumab10
    May 24, 2019 at 11:38
  • for updated question. comma "," is missing between data and success in code data: {"question": editableQuestion.innerHTML, "answer": editableAnswer.innerHTML} success:
    – xxbinxx
    May 29, 2019 at 10:43

1 Answer 1

4

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

12
  • @Oumab10 Did it helped?? what else are you looking for?
    – xxbinxx
    May 24, 2019 at 11:58
  • I have an issue with my view function, it doesn't seem to get the edited rows, plus I don't know what to fix in it, Im trying to figure it out ...
    – Oumab10
    May 24, 2019 at 12:05
  • did you understood the JS part?
    – xxbinxx
    May 24, 2019 at 12:10
  • globally yes I got the idea ( I never used Javascript I'm new to web programming)
    – Oumab10
    May 24, 2019 at 12:25
  • okay, you're doing well. Just try to use the code I gave you above. In your view you'll get the JSON data in request.POST. Try it, If you have any issues let us know but first make some efforts on your own.
    – xxbinxx
    May 24, 2019 at 12:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.