my models
class TEmail(models.Model):
CHOICES = [
('mr', 'Mester'),
('ms', "mess"),
('mrs', "mess mester")
]
subject = models.CharField(max_length=50)
message = models.TextField()
sender = models.EmailField(max_length=100, validators=[validate_email])
recepients = models.ManyToManyField('UserApp')
person = models.CharField(max_length=3, choices=CHOICES)
email_date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.sender
class UserApp(User):
CHOICES = [
('m', 'Male'),
('f', 'Female'),
('n', 'Never Want'),
]
birth_date = models.DateField()
sex = models.CharField(max_length=1, choices=CHOICES)
def __str__(self):
return self.username
forms.py
class MultiEmailField(forms.Field):
def to_python(self, value):
if not value:
return []
return value.split(',')
def validate(self, value):
super().validate(value)
for email in value:
validate_email(email)
class ContactForm(forms.ModelForm):
recepients = MultiEmailField()
class Meta:
model = TEmail
exclude = ['email_date', 'sender']
views.py
class SendEmailView(View):
def get(self, request):
form = ContactForm()
return render(request, 'sendmail/send_email.html', {'form': form})
def post(self, request):
form = ContactForm(request.POST)
if form.is_valid():
email = form.save(commit=False)
email.sender = request.user.email
for recep in form.cleaned_data['recepients']:
try:
user = User.objects.get(email=recep)
except (KeyError, User.DoesNotExist):
return render(request, 'sendmail/send_email.html',{
'error': f'This email not exist ({recep})'
})
else:
email.recepients.add(user)
form.save_m2m()
return redirect('sendmail:home')
return render(request, 'sendmail/send_email.html', {'form':form})