Can't Create Super User Django

前端 未结 2 2133
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-07 10:05

I\'m assuming that it is because my superuser depends on UserProfile which has no existing data yet. My model looks like

from django.db import models
from djang         


        
2条回答
  •  滥情空心
    2021-02-07 10:16

    I just ran into this very same issue - a profile model that is created through a migration, and a signal handler that breaks when the superuser is created using the initial syncdb.

    My solution is as follows.

    First of all, handle the case where the table doesn't exist yet. This is a bit ugly and perhaps too drastic (may mask other errors)

    @receiver(post_save, sender=User)
    def create_profile(sender, instance, created, **kwargs):
        try:
            WheelProfile.objects.get_or_create(user=instance)
        except DatabaseError:
            logging.error("Failed to create profile for %s, perhaps migrations haven't run yet?" % instance)
            from django.db import connection
            connection._rollback()
    

    Secondly, run a handler when migrations finish:

    from south.signals import post_migrate
    
    @receiver(post_migrate)
    def create_profiles(app, **kwargs):
        if app == "wheelcms_axle":
            for u in User.objects.all():
                WheelProfile.objects.get_or_create(user=u)
    

    This will of course also run when doing future migrations, creating profiles for users that don't have them. For me, that's not an issue.

提交回复
热议问题