[Django]-Python Django – update booleanField via List View

3👍

like this should look you javascript

const updateField = (order_id) =>{
    var form = new FormData();

    form.append('order_id', order_id);

    fetch('{% url "url_updateField" %}', {
      method:'post',
      body:form,
      mode:'cors',
      cache:'default',
      credentials:'include',
    }).then((response)=>{
      console.log('field update as well')
   })
})

just add a function to your button on envent onclick

{% extends "base.html" %}
{% block content %}
{% for order in orders%}
   User: {{ order.user}} | Completed: {{order.completed}} <input 
   type="checkbox" onclick="updateField({{order.pk}})">
{% endfor %}
<input type="submit">
{% endblock %}

then in your view you should have the below view to process the request

def updateField(request):
    print(request.body.get('order_id'))
    #you should update you model field here 
    return JsonResponse({'ok':True}, status=200)

This will help you How to work with ajax request with django

0👍

Combine the UpdateView with the part of the listView’s functionality by adding to the UpdateView the extra context of the entire list of objects:

class OrderUpdateView(generic.UpdateView):
    model = Order
    form_class = OrderForm

    ....

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['orders'] = Order.objects.all().order_by("-id") 
        return context

Consider a simple template where the entire list is displayed on top, and the bottom has a form allowing the user to update a particular item in the list.
This approach purposefully avoids using Ajax and javascript.

documentation

0👍

There is a way to do this without any special magic, just post to an update view from your listview with the entire form filled out correctly in hidden form fields nothing special needs to be done anywhere else.

<!-- todo_list.html -->
<form method="POST" action="update/{{object.id}}/">
    {% csrf_token %}
    <input type="hidden" name="completed" value="true" />
    <input type="hidden" name="name" value="{{object.name}}" />
    <input type="hidden" name="due_date" value="{{object.due_date|date:'Y-m-d'}}" />
    <input type="hidden" name="details" value="{{object.details}}" />
    <button type="submit" class="btn btn-primary">Not Done</button>
</form>
👤Dreded

Leave a comment