0wly
0wly

Reputation: 27

How to add multiple emails in an EmailField on a Django Model?

I'm trying to create a Client Model with an email field that can contains one or multiple email addresses.

I know that there's the EmailField type that accepts a single email address, but in my case, I need to extend this to accept multiple email addresses:

class Client(models.Model):
    company_name = models.CharField(max_length=100, unique=True)
    project = models.ForeignKey(Project, blank=True, null=True,
        on_delete=models.SET_NULL)
    email_list = models.EmailField(max_length=70)

How can I achieve this to extend email_list capacity for multiple email addresses?

Upvotes: 2

Views: 2848

Answers (2)

Ragib Shahriar
Ragib Shahriar

Reputation: 49

Use TextField

class Client(models.Model):
        bcc = models.TextField(null=True, blank=True)

Input multiple emails like this (bcc field): [email protected],[email protected]

from django.core.mail import EmailMessage

clients= Client.objects.all()
for client in clients:
    subject = client.subject
    content = client.body
    contact_email = client.msg_from
    to = client.msg_to
    bcc_mails = client.bcc
    bcc = bcc_mails.split(",")
    bcc_mails.replace('"', "")
    email = EmailMessage(
        subject,
        content,
        contact_email,
        [to],
        bcc,
        headers={'Reply-To': contact_email}
    )

Upvotes: 1

Ricardo
Ricardo

Reputation: 442

The EmailField can't be used for list.

You can create another model and use a ForeignKey

class Client(models.Model):
    company_name = models.CharField(max_length=100, unique=True)
    project = models.ForeignKey(Project, blank=True, null=True, on_delete=models.SET_NULL)


class Email(models.Model):
    client = models.ForeignKey(Client on_delete=models.CASCADE)
    email_list = models.EmailField(max_length=70)

Or a CharField like that:

class Client(models.Model):
    company_name = models.CharField(max_length=100, unique=True)
    project = models.ForeignKey(Project, blank=True, null=True, on_delete=models.SET_NULL)
    email_list = models.CharField(max_length=1000)


Client.objects.create(company_name="test", project=project_instance, email_list=json.dumps(email_list))

But the second one, I think, is not good, and you will lost the EmailField validate.

Upvotes: 4

Related Questions