PohodePES
PohodePES

Reputation: 55

django set boolean field value in views

I need to set all BooleanField values to False with button in my template.

model:

class VyberJedla(models.Model):

    nazov_jedla = models.CharField(max_length=100)
    ingrediencie = models.CharField(max_length=500)
    vybrane = models.BooleanField(default=False)

    def __str__(self):
        return self.nazov_jedla

view:

def vymazatVybrane(request):
    jedlo = VyberJedla.objects.all
    jedlo.vybrane = False
    jedlo.save()

    return redirect('/')

template(button):

<a href="{% url 'vymazatVybrane' %}">
      <button type="button">
      CHECK
      </button></a>

error: AttributeError at /vymazatVybrane 'method' object has no attribute 'vybrane'

Upvotes: 1

Views: 1431

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

If you want to set the vybrane field of all VyberJedla records to False, you should use .update(..) method [Django-doc]:

def vymazatVybrane(request):
    jedlo = VyberJedla.objects.all().update(vybrane=False)
    return redirect('/')

If you want to only set a subset of the VyberJedla records, you need to .filter(..) [Django-doc] the queryset.

Note that usually GET methods are not supposed to change entities (and their values). You might consider making this a POST/PATCH request.

Upvotes: 1

Related Questions