Django + Postgresql Object has no attribute

Asked

Viewed 70 times

0

I am trying to do a validation before submitting my form, but returns me the following error: 'Studentform' Object has no attribute 'termAccepted'

models.py of the app:

from django.db import models
from django import forms
from django.forms import ModelForm

class Student(models.Model):

    TAKE_COMPUTER_CHOICES = (
        ('sim', 'Sim'),
        ('nao', 'Não'),
    )
    COMPUTER_TYPE_CHOICES = (
        ('windows', 'Windows'),
        ('linux', 'Linux'),
        ('mac', 'Mac'),
    )

    cpf = models.CharField(
        max_length=14, unique = True, verbose_name = 'CPF')
    ra = models.CharField(
        max_length=10, unique= True, verbose_name='RA')
    email = models.EmailField(
        max_length=100, verbose_name='E-mail')
    takeComputer = models.CharField(
        max_length=3, choices=TAKE_COMPUTER_CHOICES, verbose_name='Você vai trazer seu notebook?:')
    computerType = models.CharField(
        max_length=7, choices=COMPUTER_TYPE_CHOICES, verbose_name='Qual o sistema operacional do seu notebook?:')

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    termAccepted = models.BooleanField(default=1, verbose_name='Eu li e aceito o uso da minha imagem')

    def __str__(self):
        return self.email

class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = ['cpf',
                'ra',
                'email',
                'termAccepted',
                'takeComputer',
                'computerType',]

views.py of the app:

from django.shortcuts import render, redirect
from .models import *

def create_student(request):
    form = StudentForm(request.POST or None)

    if form.is_valid() and form.termAccepted == True:
        student = form.save()
        request.session['student_id'] = student.id
        return redirect('registrations:create_student')

    return render(request, 'student-form-registration.html', {'form': form})

1 answer

1


You will have access to the form data (after validated) through the attribute .cleaned_data. So it would be something like this:

 if form.is_valid() and form.cleaned_data['termAccepted'] == True:
        student = form.save()
        request.session['student_id'] = student.id
        return redirect('registrations:create_student')

Browser other questions tagged

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