Django send_mail IntegrityError в /django-store-account/register/ - AWS ElasticBeanstalk
Я развернул свою программу на AWS ElasticBeanstalk с https (SSL) и хочу отправить письмо для проверки новым зарегистрированным аккаунтам с помощью send_mail, но получаю ошибку, указанную в заголовке, я не настроил environ
или что-то еще, весь код ниже, мой gmail тоже настроен для менее безопасных приложений
settings.py:
if DEBUG:
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'pleaeseSomebodyHireMeIWillBeTheHardestWorker@gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword bla bla bla' # important
else:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
активировать страницу: {% autoescape off %} Привет {{ user.user_name }},
Sua conta foi registrada com
https:/{{ jamelaumn.com }}{% url 'account:activate' uidb64=uid token=token %}
{% endautoescape %}
views.py
def account_register(request):
if request.user.is_authenticated:
return redirect('account:dashboard')
if request.method == 'POST':
registerForm = RegistrationForm(request.POST)
if registerForm.is_valid():
user = registerForm.save(commit=False)
user.email = registerForm.cleaned_data['email']
user.set_password(registerForm.cleaned_data['password'])
user.is_active = False
email_to = user.email
user.save()
email_subject = 'Ative sua conta'
current_site = get_current_site(request)
message = render_to_string('account/registration/account_activation_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
html_message = "<br> oi </br>"
email_body = message
send_mail(subject=email_subject, message=email_body,
from_email=settings.EMAIL_HOST_USER, recipient_list=[
email_to],
html_message=html_message)
email = EmailMessage(
email_subject,
email_body,
settings.EMAIL_HOST_USER, [email_to])
email.send()
return HttpResponse('registered succesfully and activation sent')
else:
registerForm = RegistrationForm()
return render(request, 'account/registration/register.html', {'form': registerForm})
def account_activate(request, uidb64, token):
try:
uid = urlsafe_base64_decode(uidb64)
user = UserBase.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, user.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
login(request, user)
return redirect('account:dashboard')
else:
return render(request, 'account/registration/activation_invalid.html')
forms.py:
class RegistrationForm(forms.ModelForm):
user_name = forms.CharField(
label='Coloque seu nome de Usuário', min_length=4, max_length=50, help_text='Obrigatório')
email = forms.EmailField(max_length=100, help_text='Obrigatório', error_messages={
'Obrigatório': 'Você precisa de um endereço de email'})
password = forms.CharField(label='Senha', widget=forms.PasswordInput)
password2 = forms.CharField(
label='Repita sua Senha', widget=forms.PasswordInput)
class Meta:
model = UserBase
fields = ('user_name', 'email',)
def clean_username(self):
user_name = self.cleaned_data['user_name'].lower()
r = UserBase.objects.filter(user_name=user_name)
if r.count():
raise forms.ValidationError("Usuário Já existe")
return user_name
def clean_password2(self):
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError('Senhas não são iguais')
list_of_characters = []
list_of_characters[0:-1] = cd['password'].lower()
if len(list_of_characters) < 8:
raise forms.ValidationError(
'Senha tem de ter ao menos de 8 caracteres')
confirm = "noletters"
for data in list_of_characters:
for letters in alphabet:
if data == letters:
confirm = "hasletters"
if confirm == "noletters":
raise forms.ValidationError('Precisa ter ao menos uma letra')
return cd['password2']
def clean_email(self):
email = self.cleaned_data['email']
if UserBase.objects.filter(email=email).exists():
raise forms.ValidationError(
'Já Existe um email igual cadastrado no sistema')
return email
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['user_name'].widget.attrs.update(
{'class': 'form-control mb-3', 'placeholder': 'Nome de Usuário'})
self.fields['email'].widget.attrs.update(
{'class': 'form-control mb-3', 'placeholder': 'E-mail', 'name': 'email', 'id': 'id_email'})
self.fields['password'].widget.attrs.update(
{'class': 'form-control mb-3', 'placeholder': 'Senha'})
self.fields['password2'].widget.attrs.update(
{'class': 'form-control', 'placeholder': 'Repita sua senha'})
error:
IntegrityError at /django-store-account/register/
(1062, "Duplicate entry 'dbsanznt@gmail.com' for key 'account_userbase.email'")
Request Method: POST
Request URL: https://www.jamelaumn.com/django-store-account/register/
Django Version: 4.0.3
Exception Type: IntegrityError
Exception Value:
(1062, "Duplicate entry 'dbsanznt@gmail.com' for key 'account_userbase.email'")
Exception Location: /var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/MySQLdb/connections.py, line 254, in query
Python Executable: /var/app/venv/staging-LQM1lest/bin/python
Python Version: 3.8.5
Python Path:
['/var/app/current',
'/var/app/venv/staging-LQM1lest/bin',
'/var/app/venv/staging-LQM1lest/bin',
'/usr/lib64/python38.zip',
'/usr/lib64/python3.8',
'/usr/lib64/python3.8/lib-dynload',
'/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages',
'/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages']
Server time: Mon, 30 May 2022 07:07:23 -0300