Search code examples
djangodjango-formsdjango-tables2

Edit the values from a row in the HTML table


I have a table that looks like that:

       {% for item in records %}
        <tr>
          <td>
            <form action="{% url 'update_record'%}" method="post">{% csrf_token %}
              <input  type="text" class="title" value="{{ item.title }}" size="20" maxlength="30"  />
              <input type="hidden" value={{ item.id }} name="new_title" />
              <input type="submit" value="edit" />
            </form>
          </td>
          <td>
            <input type="text" class="result" value="{{ item.results }}" size="10" maxlength="20" readonly />
          </td>
        </tr>
        {% endfor %}

Both fields (title, result) have values already but I am trying to edit their value and then send the new title value to my Django view :

@csrf_exempt
def update_record(request):
    # do things with the new title value
    sleep(3)
    return redirect('profile')

and here is my urls.py , in case it is helpful in any way:

    urlpatterns = [url(r'^update_record/', views.update_record, name='update_record'),]

I tried switching between post and get methods , using AJAX, and almost anything related I could find but nothing seems to work . The current code doesn't produce any errors but I don't see the fields at the "request.POST" dictionary.

Any method would be highly appreciated because I don't know what to try at this point except analytical Ajax classes!


Solution

  • You're almost there.

    For a field to appear in the request.POST dictionary the input field needs a name attribute.

    <form action="{% url 'update_record'%}" method="post">
        {% csrf_token %}
        <input name="item_new_title" type="text" class="title" value="{{ item.title }}" size="20" maxlength="30"  />
        <input name="item_id" type="hidden" value="{{ item.id }}"  />
        <input type="submit" value="edit" />
    </form>
    

    Here is a slightly modified version of your form but I've added/changed the name attribute of the inputs to item_new_title and item_id, as an example.

    With this form you should be able to get the value of both fields using their name attribute as the key.

    def update_record(request):
        if request.method=='POST':
            item_id = request.POST.get('item_id')
            item_new_title = request.POST.get('item_new_title')
            # do things with the new title value
    
        return redirect('profile')