geekchic
geekchic

Reputation: 2431

Django IntegrityError: (1048, "Column 'user_id' cannot be null")

This is my models.py

class Cfituser(models.Model):
user = models.OneToOneField(User)
socialid = models.IntegerField(null=True)
accesstoken = models.CharField(max_length=255L, null = True)
class Meta:
    db_table = 'CfitUser'
def __str__(self):  
      return "%s's profile" % self.user  

@receiver(post_save, sender=User)
def create_cfituser(sender, instance, created, **kwargs):  
    if created:  
        Cfituser.objects.get_or_create(user=instance) 

This is my views.py

@api_view(['GET', 'POST'])
def users_create(request, format = None):
"""
List all users, or create a new user.
"""
if request.method == 'GET':
    cfituser = Cfituser.objects.all()
    serializer = CfituserSerializer(cfituser, many=True)
    return Response(serializer.data)

elif request.method == 'POST':
    serializer = CfituserSerializer(data=request.DATA)
    if serializer.is_valid():
            print serializer.data
            user = User.objects.create_user(username = serializer.data['socialid'])
            cfituser = Cfituser.objects.get(user = user)
            cfituser.accesstoken = serializer.data['accesstoken']
            cfituser.socialid = serializer.data['socialid']
            cfituser.save()
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Whenever there is a HTTP Post request, my database tables are filled in as expected but this error keeps popping up. I've tried almost every solution available on SO but I'm stuck with this.

I have tried user = models.OneToOneField(User, null = True) but this leads to two entries in my database table, one with user_id = NULL and one with user_id = actualvalue.

Any suggestions on how to fix this?

Upvotes: 0

Views: 4156

Answers (2)

suhailvs
suhailvs

Reputation: 21680

OneToOneField means, in Cfituser.user the reverse side of the relation will directly return a single object(user.cfituser gives Cfituser). SO Cfituser.user must be unique through out the table(one and only one).

class Cfituser(models.Model):
    user = models.OneToOneField(User)
    socialid = models.IntegerField(null=True)
    accesstoken = models.CharField(max_length=255L, null = True)
    def __unicode__(self):  
         return "%s's profile" % self.user.username  


def users_create(request, format = None):
"""
List all users, or create a new user.
"""
    if request.method == 'GET':
        cfituser = Cfituser.objects.all()
        serializer = CfituserSerializer(cfituser, many=True)
        return Response(serializer.data) 
    elif request.method == 'POST':
        serializer = CfituserSerializer(data=request.DATA)
        if serializer.is_valid():
            print serializer.data
            user = User.objects.create_user(username = serializer.data['socialid'])                
            Cfituser(user = user,accesstoken = serializer.data['accesstoken'],socialid = serializer.data['socialid']).save()
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174614

Saving by default commits the entry to the database, to prevent that, pass commit=False to save(), and then do your customizations.

 serializer = serializer.save(commit=False)

 user, created = User.objects.get_or_create(username = serializer.socialid) 
 cfituser, created = Cfituser.objects.get_or_create(user = user)
 # cfituser.user = user This line is unnecessary
 cfituser.accesstoken = serializer.accesstoken
 cfituser.socialid = serializer.socialid

 cfituser.save()
 serializer.save()

You are also duplicating your efforts because your signal will also attempt to create a user. If you are on django 1.5, use customized user model; and for social registration/oauth, use django-social-auth.

Upvotes: 1

Related Questions