Good Afternoon开发者:
我对Django开发者有这个问题,我用我自己的登录做了一个小应用程序,当我使用正确的用户时我得到了这个错误<Usuario: Usuario object> is not JSON serializable
而且我没有使用json。我会告诉你我的代码:
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']
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()
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!'})
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 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
我使用的是django 1.8和python 3.4。 ty,如果你可以帮助我,是的,我会使用会议,在这里你是我的追溯,谢谢你的回复。
答案 0 :(得分:0)
我认为你的问题就在这里:
request.session['usuario']= usrLog
执行此操作时,您将Usuario
对象放入会话中,然后会话后端尝试将其序列化以将其放入数据库表中。但是,正如文档所说:
请注意,与
PickleSerializer
不同,JSONSerializer
无法处理任意Python数据类型。
(有关来源,请参阅here。整个页面实际上是一个很好的阅读。)JSONSerializer
是1.6及以上的默认值。我不建议切换到PickleSerializer
以解决它所带来的安全问题。
您可以执行的操作不是将request.session['usuario']
设置为整个Usuario
对象,而是将主键存储在那里,并在需要时检索相应的Usuario
对象。所以:
request.session['usuario']= usrLog.pk