Click the Save button and change boolean Django 2.0

Asked

Viewed 355 times

2

Gentlemen, I’m studying Django 2.0, and I’m having a problem, by clicking save I want to change the boolean database of False for True, and I have no idea how to do that.

If anyone can help me?

Follows short code:


py.models

from django.db import models

class Espera(models.Model):

   ...

   cancelaEspera = models.BooleanField(default=False,  blank=True)
   obsCancelamentoEspera = models.TextField('Observações', null=True, blank=True)

   def __str__(self):
    return "%s %s" % (self.dataEspera)

form py.

from django.forms import ModelForm
from . import models

...

class cancelaEsperaForm(ModelForm):
class Meta:
    model = models.Espera
    fields = ['obsCancelamentoEspera']

view py.

from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from . import models, forms, urls

...

def cancelarEspera(request, id):
    cancela = get_object_or_404(models.Espera, pk=id)
    form = forms.cancelaEsperaForm(request.POST or None, request.FILES or None, instance=cancela)

    if form.is_valid():
        form.save()      
        return redirect('listaEspera')

    return render(request, 'espera//cancelaEspera.html', {'form': form})

html template.

{% extends 'base.html' %}

{% block main %}

    <div class="card">
        <form method="POST">
            {% csrf_token %}

            <h1> Cancelamento da Espera </h1>

            <p> Qual o motivo do Cancelamento? </p>    

            {{ form|bootstrap }}                        

            <h2> Tem certeza que deseja cancelar essa espera?</h2>

            <button type="submit" > Sim </button>
            <a href="{% url 'listaEspera' %}" method="get" > Não </a>       

        </form>
    </div>

{% endblock %}
  • Within form you must inform which fields will be displayed on the page, and you just entered the field obsCancelamentoEspera

  • mine form py. It’s too big I thought it was unnecessary to put it all together, so the reticence, I decided to go straight to the problem. But if it’s really necessary, I put ḿais data.

  • you put fields = ['obsCancelamentoEspera'], lacked to put the cancelaEspera within that list.

  • @Paul, putting in the fields the cancelaEspera only a checkbox will appear in the template to mark the completion. I do not want a checkbox, I want to click the button YES and the cancelaEspera becomes True automatically, without check box marking.

1 answer

0


If you just want to change the field value BooleanField, alter in this way:

if form.is_valid():
    form_ = form.save(commit=False)
    form_.cancela = True
    form_.save()
    return redirect('listaEspera')
  • 1

    worked, thanks, just made the change: On line 3: form_.cancelaEspera = True

Browser other questions tagged

You are not signed in. Login or sign up in order to post.