-1

Good Afternoon developers:

I have this question for Django Developers, well i did a litte app with my own login, when i used a correct user i get this error <Usuario: Usuario object> is not JSON serializable and i'm not using json. i will show you my code:

models.py:

from django.db import models
from django.core.exceptions import ValidationError

from db.managers import TipoUsuarioManager, UsuarioManager, MenuManager, MenuTipoUsuarioManager

#-------------------------------------------------------------------#

#----------Modelo Tipo Usuario-------#

class TipoUsuario(models.Model):

    def validate_vacio_nulo(valor):
        if(valor == '') or (valor == None) or (len(valor) < 3):
            raise ValidationError(u'%s no se puede' % valor)

    nombre   = models.CharField(max_length=100, validators = [validate_vacio_nulo])
    created  = models.DateTimeField(auto_now_add=True) # Usar datetiem.data.today() = import datetime
    updated  = models.DateTimeField(auto_now=True)

    objects= TipoUsuarioManager()

    def __unicode__(self):
        return u'%s' % (self.nombre)

 #-------------------------------------------------------------------------------------#}

 #-----------------Modelo Usuario ------------------#

class Usuario(models.Model):
    tipousuario = models.ForeignKey(TipoUsuario)
    nombre      = models.CharField(max_length=100)
    login       = models.CharField(max_length=100)
    clave       = models.CharField(max_length=100)
    email       = models.EmailField()
    created     = models.DateTimeField(auto_now_add = True)
    updated     = models.DateTimeField(auto_now=True)

    objects = UsuarioManager()

    def __unicode__(self):
        return u'%s - %s' % (self.login, self.nombre)


    class Meta:
        ordering= ['tipousuario', 'nombre']

 #-------------------------------------------------------------------------------------#

 #------------------- Modelo Menu ------------------------#

class Menu(models.Model):
    nombre = models.CharField(max_length=100)
    url    = models.CharField(max_length=100, blank=True, null=True)
    action = models.CharField(max_length=100, blank=True, null=True)
    icono  = models.CharField(max_length=100, blank=True, null=True)
    padre  = models.IntegerField()
    orden  = models.IntegerField()
    created= models.DateTimeField(auto_now_add = True)
    updated= models.DateTimeField(auto_now=True)
    tipousuario = models.ManyToManyField(TipoUsuario, blank=True, null=True)

    objects= MenuManager() #Para usar managers

def __unicode__(self):
        return u'%s' % (self.nombre)

class Meta:
      ordering= ['padre','orden']




class MenuTipoUsuario(models.Model):
    menu = models.ForeignKey(Menu)
    tipousuario = models.ForeignKey(TipoUsuario)

    objects= MenuTipoUsuarioManager() #Para Usar Managers

    class Meta:
        #db_table= u'db_menu_tipousuarios'
        ordering= ['tipousuario','menu']

managers.py:

from django.db import models

class TipoUsuarioManager(models.Manager):

    def todos(self):
        return self.model.objects.all()

class UsuarioManager(models.Manager):

    def todos(self):
        return self.model.objects.all()

    def login_ok(self, usuario, clave):
        try:
            existe= self.model.objects.get(login= usuario, clave= clave)

        except self.model.DoesNotExist:
            return None
        else:
            return existe


    def cambio_clave(self, id, actual, nueva):
        usuario= self.model.objects.get(id= id)
        if usuario.clave != actual: return False
        usuario.clave= nueva
        usuario.saved()
        return True




#-----------------------------------------------------------------------------------------#

class MenuManager(models.Manager):

    def todos(self):
        return self.model.objetcs.all()

class MenuTipoUsuarioManager(models.Manager):

    def todos(self):
        return self.model.objetcs.all()

forms.py:

from django import forms
from db.models import TipoUsuario, Usuario, Menu, MenuTipoUsuario

class IngresoForm(forms.Form):
    usuario= forms.CharField(error_messages={'required':'Espacio Requerido!'})
    clave= forms.CharField(widget=forms.PasswordInput(),
           error_messages={'required':'Espacio Requerido!'})

views.py:

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect

from db.forms import IngresoForm, CambioPwdForm
from db.models import Usuario

# Create your views here.
def index(request):
    return render_to_response('home/index.html', locals(), context_instance = RequestContext(request))

def acerca_de(request):
    return render_to_response('home/acerca_de.html', locals(), context_instance = RequestContext(request))

def ingreso(request):
# formulario - msg_no - ver_error - lista_err: se deben llamar asi, el include las referencia con ese nombre
    valido= False
    ver_error= False
    msg_no='Ingreso no valido'
    lista_err= []

    if request.method == 'POST':
        formulario= IngresoForm(request.POST)
        valido= formulario.is_valid()
        if valido:
            usuario= formulario.cleaned_data['usuario']
            clave=  formulario.cleaned_data['clave']
            usrLog= Usuario.objects.login_ok(usuario,clave)
            if usrLog != None:
                request.session['usuario']= usrLog
                return HttpResponseRedirect('/index/')
            else:
                ver_error= True

        else:
            ver_error= True
            for field in formulario:
                for error in field.errors:
                    lista_err.append(field.label + ': '+error)

    else:
        formulario= IngresoForm()

    return render_to_response('home/ingreso.html', locals(), context_instance = RequestContext(request))

def cambio_clave(request):
    return render_to_response('home/cambio_clave.html', locals(), context_instance = RequestContext(request))

def salir(request):
    #del request.session['usuario']
    return HttpResponseRedirect('/index/')

Traceback:

Traceback Switch to copy-and-paste view

C:\Python34\lib\site-packages\django\core\handlers\base.py in get_response
                response = middleware_method(request, response) ...
▶ Local vars
C:\Python34\lib\site-packages\django\contrib\sessions\middleware.py in process_response
                    request.session.save() ...
▶ Local vars
C:\Python34\lib\site-packages\django\contrib\sessions\backends\db.py in save
            session_data=self.encode(self._get_session(no_load=must_create)), ...
▶ Local vars
C:\Python34\lib\site-packages\django\contrib\sessions\backends\base.py in encode
        serialized = self.serializer().dumps(session_dict) ...
▶ Local vars
C:\Python34\lib\site-packages\django\core\signing.py in dumps
        return json.dumps(obj, separators=(',', ':')).encode('latin-1') ...
▶ Local vars
C:\Python34\lib\json\__init__.py in dumps
        **kw).encode(obj) ...
▶ Local vars
C:\Python34\lib\json\encoder.py in encode
        chunks = self.iterencode(o, _one_shot=True) ...
▶ Local vars
C:\Python34\lib\json\encoder.py in iterencode
        return _iterencode(o, 0) ...
▶ Local vars
C:\Python34\lib\json\encoder.py in default
        raise TypeError(repr(o) + " is not JSON serializable") ...
▶ Local vars

I'm using django 1.8 and python 3.4. ty if you can help me, yes i'm using sessions and here you are my traceback thank you for anwser.

2
  • Do you use sessions? Data is jsonified for sessions.
    – Matthias
    Oct 6, 2014 at 17:09
  • You should post the full traceback, which will give us (and you) some clues about where to look. Oct 6, 2014 at 17:47

1 Answer 1

0

It looks to me that your problem is here:

request.session['usuario']= usrLog

When you do this, you are putting a Usuario object into the session, and then the session backend tries to serialize it to put it into a database table. However, as the documentation says:

Note that unlike PickleSerializer, the JSONSerializer cannot handle arbitrary Python data types.

(See here for the source. The whole page is actually a good read.) JSONSerializer is the default for 1.6 and up. I do not recommend switching to PickleSerializer for the security issues it entails.

What you could do instead of setting request.session['usuario'] to a whole Usuario object is store the primary key there and the retrieve the corresponding Usuario object when you need it. So:

request.session['usuario']= usrLog.pk
1
  • Thank you for the help, that you said help me to find the problem, this was request.session['usuario']= usrLog needed to put the attribute of the object request.session['usuario']= usrLog.login, if y want to add other attributes i need to put request.session['nombre']= usrLog.nombre and after call this sessions parms in the view. Thank you so much again. Oct 8, 2014 at 7:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.