Test and patch from #22325 - custom user model breaks migrations

This is an attempt to fix #22325 by adding a test and applying the patch from the ticket. However, while the patch did solve the problem in my *real* code, it didn't manage to fix the test.

This could be due to an error in my test but after spending some time on it, I can't find it. Would love more eyes on it.