Ro0t
Ro0t

Reputation: 179

how to check the status of boolean field in django views

I'm using django 1.11.3.

The model.py file:

class Corso(models.Model):
titolo = models.CharField(max_length=100)
progressivo= models.BooleanField(default=False)

f1= models.BooleanField(default=False)
f2= models.BooleanField(default=False)

def __str__(self):
    return str(self.titolo)

The views.py file:

def edit_iscrizioni(request, corso_id):
corsi = Corso.objects.filter( pk=corso_id)
tabella= Iscrizione.objects.filter(user=request.user)
iscrizione=get_object_or_404(Iscrizione, pk=tabella)

f1=CreaCorsi.objects.values_list("f1")

print f1

if request.method == "POST":
    form = IscrizioneForm(request.POST, instance= iscrizione)
    if form.is_valid():
        iscrizione = form.save(commit=False)
        iscrizione.user = request.user
        iscrizione.published_date = timezone.now()
        iscrizione.corso1_id= corso_id
        iscrizione.save()


    return redirect('privata')

else:
    form = IscrizioneForm(instance= iscrizione)
return render(request, 'corsi/edit.html', {'form':form, 'corsi':corsi})

How to make a view.py with this logic?

if Corso.f1==True:

I know x=Corso.objects.filter(f1=True) but I don't want to use it.

Upvotes: 2

Views: 2364

Answers (1)

scharette
scharette

Reputation: 9977

Your question is vague but if I understand correctly, you are getting the right object with this line :

corsi = Corso.objects.filter(pk=corso_id)

So if your goal is to compare his f1 attribute, why not using :

if corsi.f1:
    #do something when True

EDIT

Sorry it was my mistake, the line you use return a Queryset,

corsi = Corso.objects.filter(pk=corso_id)

Therefore use this:

corsi = Corso.objects.get(pk=corso_id)

Which will result in an instance and then use my conditional code.

Another alternative would be to use built-in first() this will add a validation to check if the object exists. Then, you have to decide what you want to do if it is None. Use it like this:

corsi = Corso.objects.filter(pk=corso_id).first()

Upvotes: 2

Related Questions