Django admin EmailField with null=True, blank=True, unique=True saves empty string ("") instead of null

When I use Django EmailField with null=True, blank=True, unique=True, admin saves empty string ("") instead of null. So I recieve "User with this Email address already exists." error.

As this ticket says this problem must be solved and it's OK when I use CharField but not EmailField. Is there any way to solve this?

To resolve this issue, you need to convert empty strings to None before saving the data to the database. One way to do this is by overriding the save() method in your model.

from django.db import models

class MyUser(models.Model):
    email = models.EmailField(null=True, blank=True, unique=True)
    
    def save(self, *args, **kwargs):
        # Convert empty string to None for the email field
        if self.email == '':
            self.email = None
        super(MyUser, self).save(*args, **kwargs)

I hope this will help you a little.

you can add a clean method for this, ie if value for email is '' then with clean method, you can add custom value to email and save it in db.

you can do this as

class Mymodel(models.Model):
    email =  models.EmailField(null=True, blank=True, unique=True)
    
    def clean(self):
        if self.email == '':
            self.email=None
        super().clean()
Вернуться на верх