5

I have started a django project with extending User model from AbstractUser to my custom model which have foreign key relation with other model. When I try to create superuser with manage.py it does not create a superuser for testing giving me IntegrityError. I know that there is no records in RoleModel then how do I handle this situation. I will take Role while Teacher Signs up to the site. Any help will be appreciated

class TeacherModel(AbstractUser):
    middle_name = models.CharField(max_length=256)
    role = models.ForeignKey(RoleModel, on_delete=models.DO_NOTHING, null=True)
Appyens
  • 129
  • 1
  • 7

3 Answers3

1

First, you will need to add the REQUIRED_FIELDS list on the AbstractUser class with the additional fields that you want the user to be prompted with when creating a superuser with the createsuperuser management command. See the docs here

Secondly, you will have to create and use a custom UserManager on your custom user model which handles the additional fields you added to the user model when creating a new user.

You can refer to this Django GitHub commit which introduced that support on how to implement the functionality. The code is straightforward and easy to understand.

You may also need a few other customisations for all to work well. See this full example given in the Django docs.

Erick M
  • 465
  • 4
  • 9
0

Exception raised when the relational integrity of the database is affected, e.g. a foreign key check fails, duplicate key, etc.

Here is answer: IntegrityError in Django

0

Firstable, what do you want to do, extend or custom the User Model?

If you want to extend... It's enough with a foreign key. For this, the Django project recommends using OneToOneField(User).

You could use OneToOneField(TeacherModel) in your RoleModel

In this case, see the link below.

https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#extending-the-existing-user-model

In the other hand, if you want to custom the User model, you must have to do this before doing the migrations. The initial setup must have your customization. You can create an app only for the User Model customization.

In this case, see the links below.

https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#substituting-a-custom-user-model

https://wsvincent.com/django-tips-custom-user-model/

I hope this helped you

Samir Hinojosa
  • 825
  • 7
  • 24