Home > Enterprise >  I have a two Model related to each other and I want to automatically create the data on ModelB upon
I have a two Model related to each other and I want to automatically create the data on ModelB upon

Time:11-16

I have this User Model Which came from the User of Django Admin

class NewUser(AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(_('email address'), unique=True)
    user_name = models.CharField(max_length=150, unique=True)
    first_name = models.CharField(max_length=150)
    start_date = models.DateTimeField(default=timezone.now)
    is_staff = models.BooleanField(default=True)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

    objects = CustomAccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['user_name', 'first_name']

    def __str__(self):
        return str(self.id)   " "   self.email

And I have another model related to this User model called Promoter model

class Promoter(models.Model):
    user = models.ForeignKey(
        NewUser,
        on_delete=models.CASCADE,
    )

    def __str__(self):
        return str(self.user.id)   " "   self.user.email

    def email(self):
        return self.user.email

And every time I added a data into User I want to Automatically add also a data into the Promoter model with a link to newly created User

This is my code in added/registering a new User

class RegisterView(APIView):
    permission_classes = [AllowAny]

    def post(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            newuser = serializer.save()
           

            if newuser:
                return Response(status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I try to manually add the newly created User into the front end by having a two different API call both for adding User and adding promoter but I'm getting an error in adding a Promoter data manually (1048, "Column 'user_id' cannot be null")

I also try to adding data using postman enter image description here

CodePudding user response:

It's an error for user field saved without adding the user object of foreign key

you can pass the user object in the save() method like this...

def post(self, request):
    serializer = UserSerializer(data=request.data)
    if serializer.is_valid():
        newuser = serializer.save(user=request.user)
  • Related