Django session, issue: Object of type '' is not JSON serializable

0

I am creating a student but when I try to save it inside a session, it returns the following error:

Object of type 'Student' is not JSON serializable

No settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions', <---- já esta no INSTALED_APPS
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bootstrap4',
    'registrations',
    
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware', <---- já esta no MIDDLEWARE
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

app views.py:

from django.shortcuts import render,  redirect
from .models import Student, StudentForm, StudentDescriptionForm, ParentStudent, ParentStudentForm

# LISTAR TODOS OS ALUNOS


def list_students(request):
    students = Student.objects.all()
    return render(request, 'students.html', {'students': students})

# CRIAR UM NOVO ALUNO


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

    if form.is_valid():
        student = Student(**form.cleaned_data)
        print(student)
        request.session['student'] = student <--- inicio a sessão
        form.save()
        return redirect('registrations:parent_student')

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

# CRIAR UM NOVO RESPONSÁVEL / PAI


def parent_student(request):
    form = ParentStudentForm(request.POST or None)

    if form.is_valid():
        parent_student = ParentStudent(**form.cleaned_data)
        print(parent_student)
        form.save()
        return redirect('registrations:list_students')

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


# INSERIR A DESCRIÇÃO NO ALUNO


def student_description(request, id):
    student = Student.objects.get(id=id)
    form = StudentDescriptionForm(request.POST or None, instance=student)

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

    return render(request, 'student-description-form.html', {'form': form , 'student': student})
    
asked by anonymous 21.08.2018 / 20:36

1 answer

3

I believe you can change it to the following form:

At the beginning of your script:

 from django.forms.models import model_to_dict

In the part you save in the session:

 request.session['student'] = model_to_dict(student)

I would particularly prefer to save only the id in the session, to retrieve it later.

Something like:

 request.session['student_id'] = student.id

Then you could query through student_id .

I got the idea for this answer on SOEN

    
21.08.2018 / 22:48