Django custom user and django admin

#views.py

def destroy(self, request,pk, *args, **kwargs):
        employee = get_object_or_404(Employee, pk=pk)
        user = CustomUser.objects.filter(id = employee.user.id)
        print('employee', employee)
        print('user', user)
        employee.delete()
        user.delete()  # manually delete linked user
        return Response({"detail": "Employee and user deleted successfully."}, 
        status=status.HTTP_204_NO_CONTENT)

#models.py

#Base model

class BaseModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

#Custom user model

class CustomUser(AbstractBaseUser,BaseModel):
    EMPLOYEE = "employee"
    CLIENT = "client"
    USER_TYPE_CHOICES = [
        ( EMPLOYEE, 'Employee'),
        (CLIENT, 'Client'),
    ]

    email = models.EmailField(unique=True, validators=[email_validator])
    is_active = models.BooleanField(default=True)
    is_superuser = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    user_type = models.CharField(max_length=10, choices=USER_TYPE_CHOICES)
    username = None  # Remove username field since we use email for login

    objects = CustomUserManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["user_type"]

    def __str__(self):
        return f"{self.email} - {self.user_type}"

#Employee model

class Employee(BaseModel):

    MALE = "Male"
    FEMALE = "Female"
    OTHER = "Other"
    GENDER_CHOICES = [
        (MALE, "Male"),
        (FEMALE, "Female"),
        (OTHER, "Other"),
    ]
    
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, 
    related_name="employee")
    name = models.CharField(max_length = 250)
    father_name = models.CharField(max_length=250)
    contact_no = models.CharField(max_length=250, validators=[contact_no_validator])
    alternate_contact_no = models.CharField(max_length=15, validators=[contact_no_validator], 
    null=True, blank=True)
    gender = models.CharField(max_length=10, choices= GENDER_CHOICES, default=MALE)
    pan_no = models.CharField(max_length=20)
    aadhar_no = models.CharField(max_length=12, validators=[aadhar_no_validator])
    dob = models.DateField(null=True, blank=True)
    department = models.ForeignKey(Department, on_delete=models.SET_NULL, 
    related_name="department_employees", null=True)
    designation = models.ForeignKey(Designation, on_delete= models.SET_NULL, 
    related_name="designation_employees", null=True)
    joining_date = models.DateField()
    # role = models.ForeignKey()
    basic_salary = models.IntegerField()
    
    
    def __str__(self):
        return self.name



#settings.py
# User authentication model 
AUTH_USER_MODEL = "app.CustomUser"

whenever I am trying to delete user i am getting the error of

django.db.utils.ProgrammingError: operator does not exist: integer = uuid LINE 1: ...django_admin_log" WHERE "django_admin_log"."user_id" IN ('277d3... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts.

can anyone help me ?

You likely changed your id field in BaseModel from integer to uuid after your initial migration. This has resulted to a mismatch between the original data type of id (integer) which the database expects and the modified data type (uuid) which you used. Changes like this should be done before your initial migration not after.

If you are still in Development and have nothing to lose, you can resolve it by dropping the database and recreating it again. For example, when faced with the same error, I remember having to run in dbshell:

DROP DATABASE <database_name>;

and then recreate the database again before running migrations again. Please only use this solution if in development.

Use a custom Admin logging system or skip deleting users who are linked to LogEntry is the one I am recommend.

But in your case, since you are deleting users manually (not from the admin), the better is, change as follows,

views.py

        user = CustomUser.objects.filter(id = employee.user.id)
        print('employee', employee)
        print('user', user)
        employee.delete()

Try following code instead above,

        user = CustomUser.objects.get(id=employee.user.id)
        employee.delete()
        try:
            user.delete()
        except Exception as e:
            print("Error deleting user:", e)
Вернуться на верх