[Answer]-Django IntegrityError: (1048, "Column 'user_id' cannot be null")

1👍

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.

0👍

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)

Leave a comment