Update the record server-sided without form

I have a ListView which I render in a

with the following
<td><input class="form-check-input" type="checkbox" onclick="location.href='{% url 'navbar-change' navbar.pk %}'" name="" value="" {% if navbar.active %} checked {% endif %}></td>

When the user clicks a checkbox I want to update the record server-sided without returning a form, I think this code does what I want:

object = models.Navbar.objects.get(pk=pk).update(active=Case(
    When(active=True, then=False), default=True)
)

However, I don’t now where to put these lines a of code. ‘navbar-change’ routes to:

class NavbarChangeView(PermissionRequiredMixin, UpdateView):
    permission_required = 'settings.change_navbar'

I had a look at CCBV, and I’m not sure whether UpdateView is the right choice in this case, I don’t need a form.

Kind regards,

Johanna

You are correct that an UpdateView really isn’t needed here.

A simple function-based view would be sufficient.

You don’t show your url definition, but assuming a url parameter like <int:pk> you could use something like this:

@permission_required('settings.change_navbar')
def navbar_change_view(request, pk):
    models.Navbar.objects.filter(pk=pk).update(active=Case(When(is_closed=True, then=False), default=True)

    # Up to you to decide what happens after the click is processed.
    return SomeHttpResponse 

Note that get doesn’t return a queryset - it returns an instance of the model. That instance doesn’t have an update attribute - that’s a function call on a queryset.

Hi Ken,

Thanks for your reply and the code example.

Your reamrk on get not returning a queryset had me take another look at the QuerySet API reference. Now I understand the implication of ‘methods that return new querysets’ and ‘methods that do not return a queryset’.

Kind regards,

Johanna