我从默认值为False的BooleanField中收到错误。出于某种原因,当我登录时遇到错误,指出变量(结尾)不能为null。
当我将字段更改为NullBooleanField时,我可以登录,并且当我在admin中检查实例时,该字段仍显示为空。
错误:
“结束”列中的空值违反了非空约束
models.py
class UserSessionManager(models.Manager):
def create_new(self, user, session_key=None, ip_address=None):
session_new = self.model()
session_new.user = user
session_new.session_key = session_key
if ip_address is not None:
city_data = get_client_city_data(ip_address)
session_new.ip_address = ip_address
session_new.location = Location.objects.create_new(data=city_data)
session_new.save()
return None
class UserSession(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
ip_address = models.CharField(max_length=220, blank=True, null=True)
session_key = models.CharField(max_length=100, blank=True, null=True)
timestamp = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=True)
ended = models.BooleanField(default=False)
location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name='location')
objects = UserSessionManager()
def __str__(self):
return str(self.user.username)
def end_session(self):
session_key = self.session_key
ended = self.ended
try:
Session.objects.get(pk=session_key).delete()
self.active = False
self.ended = True
self.save()
except:
pass
return self.ended
def post_save_session_receiver(sender, instance, created, *args, **kwargs):
if created:
qs = UserSession.objects.filter(user=instance.user, ended=False, active=False).exclude(id=instance.id)
for i in qs:
i.end_session()
if not instance.active and not instance.ended:
instance.end_session()
if FORCE_SESSION_TO_ONE:
post_save.connect(post_save_session_receiver, sender=UserSession)
def post_save_user_changed_receiver(sender, instance, created, *args, **kwargs):
if not created:
if instance.is_active == False:
qs = UserSession.objects.filter(user=instance.user, ended=False, active=False)
for i in qs:
i.end_session()
if FORCE_INACTIVE_USER_ENDSESSION:
post_save.connect(post_save_user_changed_receiver, sender=User)
def user_logged_in_receiver(sender, instance, request, *args, **kwargs):
user = instance
ip_address = get_client_ip(request)
session_key = request.session.session_key # Django 1.11
UserSession.objects.create_new(
user=user,
ip_address=ip_address,
session_key=session_key,
)
user_logged_in_.connect(user_logged_in_receiver)