Error saving ForeingKey with Post_save in User profile

2

I am creating the user profile with post_save signal , but I have a field foreign key that It's not being saved, and I do not see any way to solve it. I did it like this: All this from the django admin.

  

The error is: 1048, "Column 'company_id' can not be null")

MODELS.PY

#!
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse

#from django.db.models import signals
from django.db.models.signals import post_save
from django.dispatch import receiver


class Empresa(models.Model):
    nombre = models.CharField(max_length=255)
    descripcion = models.TextField(max_length=200)
    slug = models.SlugField()
    created = models.DateTimeField(auto_now_add=True, editable=False)
    last_updated = models.DateTimeField(auto_now=True, editable=False)

    class Meta:
        ordering = ('-created',)

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



TIPO_USUARIO = (
    (0, 'Administrador'),
    (1, 'Tecnico'),
    (2, 'Finanzas'),
    (3, 'Cliente'),
)


class PerfilUsuario(models.Model):  
    #DEFAULT_PK=1
    user = models.OneToOneField(User)#si es un cliente el nombre sera EJ: cliente@empresa
    empresa = models.ForeignKey(Empresa, related_name='empresa_administradores')
    #cuando se registren por default entren al grupo Admin, 
    tipo_usuario = models.PositiveSmallIntegerField(choices=TIPO_USUARIO, verbose_name="¿Que tipo de Usuario es?", default=0) 


    def __unicode__(self):
        return u'Perfil de: %s' % self.user.username


def create_user_profile(sender, instance, created, **kwargs):
    if created:
        PerfilUsuario.objects.get_or_create(user=instance)
        print "ssssssss"
        print instance.empresa
        PerfilUsuario.empresa = instance.empresa
        PerfilUsuario.save()
post_save.connect(create_user_profile, sender=User)



class Cliente(models.Model):

    nombre_rb = models.CharField(max_length=70, verbose_name="Nombre de usuario en RB(queue, hotspot, PPPoE)")
    ip = models.GenericIPAddressField()
    slug = models.SlugField()
    created = models.DateTimeField(auto_now_add=True, editable=False)
    last_updated = models.DateTimeField(auto_now=True, editable=False)
    # Relationship Fields
    perfil = models.OneToOneField(PerfilUsuario, )

    class Meta:
        ordering = ('-created',)

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

ADMIN.Py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from .models import *
# Register your models here.

#Agrego el perfil del usuario al admin
class PerfilInline(admin.StackedInline):
    model = PerfilUsuario
    can_delete = False
    verbose_name_plural = 'Perfil'

#Defino el nuevo UserAdmin
class UserAdmin(UserAdmin):
    inlines = (PerfilInline, )

# Se vuelve a registar UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

class EmpresaAdmin(admin.ModelAdmin):
    model=Empresa
    prepopulated_fields = {"slug": ("nombre",)}

admin.site.register(Empresa, EmpresaAdmin)


class ClienteAdmin(admin.ModelAdmin):
    model=Cliente
    prepopulated_fields = {"slug": ("nombre_rb",)}

admin.site.register(Cliente, ClienteAdmin)

Please can you tell me, what am I doing wrong in post_save ? Thank you very much.

SOLUTION: It was not necessary to run the Post_save signal, since it was working from the admin. When I have to create a form in my template, I will check if this problem happens. So far it works. Thanks @deoxyseia

    
asked by oscar 13.10.2016 в 17:22
source

1 answer

0

Friend, I know what your mistake is ... if the code is currently this way, you have the following problem ...

This is your current function

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        PerfilUsuario.objects.get_or_create(user=instance)
        print "ssssssss"
        print instance.empresa
        PerfilUsuario.empresa = instance.empresa
        PerfilUsuario.save()
post_save.connect(create_user_profile, sender=User)

If you realize ... you are calling your model PerfilUsuario and you are in the 3rd line seeing if it exists or not, but you do not keep it in a variable in memory ... you just called it and you left it to your luck ... in the 6th line, you do the same, you assign a class to the class, but you did not do it with an instance of the class, obviously in the save () it would throw error

try to instantiate your object, like this:

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        perfil, creado = PerfilUsuario.objects.get_or_create(user=instance)
        print "ssssssss"
        print instance.empresa
        perfil.empresa = instance.empresa
        perfil.save()
post_save.connect(create_user_profile, sender=User)
    
answered by 14.10.2016 / 16:50
source