Ankzious
Ankzious

Reputation: 325

Custom User Model with multiple Unique id - Django RestFramework

Hi StackOverFlow buddies, I have created a custom User model for my project and would like to register the Users with Restframework.

I want Custom User model to have 2 unique fields together, for which I followed "Official doc" for unique_together property. It seems to be only taking only 1 field (ie email for my case), as a unique one.

Relevant piece my code until this point looks like this: PS: Let me know if more info is required.

models.py

class MasterUser(AbstractBaseUser):
    email = models.EmailField(verbose_name='email address',max_length=255,unique=True,)
    firstname = models.CharField(max_length=100,blank=True)
    contact = models.CharField(max_length=100, blank=True)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['firstname']
    class Meta:
        unique_together = (('email', 'contact'),)

serializer.py

class RegisterUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(style={'input_type': 'password'}, write_only= True)

    class Meta:
        model = MasterUser
        fields = ('firstname', 'password', 'password2', 'email','contact')
        extra_kwargs = {
            'password': {'write_only': True},
        }

    def save(self):
        account = MasterUser(
            email = self.validated_data['email'],
            firstname = self.validated_data['firstname'],
            contact = self.validated_data['contact'],
        )

        password = self.validated_data['password']
        password2 = self.validated_data['password2']
        if password != password2:
            raise serializers.ValidationError({'password': 'Password doesnt matches'})
        account.set_password(password)
        account.save()
        return account

views.py

@api_view(['POST'])
def registration_view(request):
    if request.method == "POST":
        serializer = RegisterUserSerializer(data= request.data)
        data = {}
        if serializer.is_valid():
            account = serializer.save()
            data['response'] = "Successfully registered new user!"
        else:
            data = serializer.errors
        return Response(data)

Where am I missing to implement thing?

Upvotes: 0

Views: 447

Answers (1)

Jerven Clark
Jerven Clark

Reputation: 1219

unique_together means the set of fields you defined should be unique for all Users. If you also want contact to be a unique field when stored in db, you should pass the unique parameter like so:

class MasterUser(AbstractBaseUser):
    ...
    contact = models.CharField(max_length=100, blank=True, unique=True)
    ...

Upvotes: 2

Related Questions