Home > Software engineering >  Why my function in django to change a BooleanField is not working?
Why my function in django to change a BooleanField is not working?

Time:08-24

I'm trying to change a BooleanField from a model in django, using the post method activated with a button but is not working, the post method from the button is working but the function is not doing what it should do. When i change the boolean value in the admin tool it's work, i think probable the problem is in the function but i don't know whats is the problem.

This is my function:

def close(request, listing_id):
    listing = Listing.objects.get(id=listing_id)
    if request.method == "POST":
        listing.active = False
        listing.save()
        messages.success(request, 'You closed the Auction!')
            
    return redirect(reverse("listing", args=[listing_id]))

The BooleanField whats i want to change it's call "active" (true by default).

and this is the button:

<form action="{% url 'close' listing.id %}" method="post" >
   {% csrf_token %}
    <button  type="submit" name="action" value="close" >Close Auction</button>
</form>

CodePudding user response:

Your code looks correct, but I use a little bit different and it's working for me. I don't use the action attribute in the form. By the way I'm using Django 4.0.7.

Below is an example:

views.py:

def items(request, slug, pk):
    next = request.POST.get('next', '{% url "process" slug=slug %}')
    item = Items.objects.get(item_id=pk)

    if request.POST.get('start', False):
        item.started = True     # BooleanField 'started' (default = False, setted in the Items model)
        item.save()
        return HttpResponseRedirect(next)
    else:
        return render(request, 'items.html', {'slug':slug, 'pk':pk})

template:

<form method="post" >
   {% csrf_token %}
    <button type="submit" name="start" value="start" >Start</button>
</form>

CodePudding user response:

As you mentioned, you want:

The BooleanField whats i want to change it's call "active" (true by default).

You can simply set default option as default=True to the field, so:

class Listing(models.Model):
    active=models.BooleanField(default=True)
   
  • Related