Я пытаюсь сделать почтовую подписку на своем django веб-сайте. Я следовал инструкциям в Интернете о том, как этого добиться. Я прошел через это тщательно, но всякий раз, когда я вхожу и пишу по электронной почте, появляется сообщение об ошибке HTTP 401: не авторизовано. Я перебрал инструкции и не смог найти, где ошибся.
Код настроек FROM_EMAIL = 'newsletter@example.com' # замените своим адресом SENDGRID_API_KEY = os.environ.get ('SENDGRID_API_KEY')
Код модели:
class Subscriber(models.Model):
email = models.EmailField(unique=True)
conf_num = models.CharField(max_length=15)
confirmed = models.BooleanField(default=False)
def __str__(self):
return self.email + " (" + ("not " if not self.confirmed else "") + "confirmed)"
class Newsletter(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
subject = models.CharField(max_length=150)
contents = models.FileField(upload_to='uploaded_newsletters/')
def __str__(self):
return self.subject + " " + self.created_at.strftime("%B %d, %Y")
def send(self, request):
contents = self.contents.read().decode('utf-8')
subscribers = Subscriber.objects.filter(confirmed=True)
sg = SendGridAPIClient(settings.SENDGRID_API_KEY)
for sub in subscribers:
message = Mail(
from_email=settings.FROM_EMAIL,
to_emails=sub.email,
subject=self.subject,
html_content=contents + (
'<br><a href="{}/delete/?email={}&conf_num={}">Unsubscribe</a>.').format(
request.build_absolute_uri('/delete/'),
sub.email,
sub.conf_num))
sg.send(message)
Views.py
def random_digits():
return "%0.12d" % random.randint(0, 999999999999)
@csrf_exempt
def subscribe(request):
if request.method == 'POST':
sub = Subscriber(email=request.POST['email'], conf_num=random_digits())
sub.save()
message = Mail(
from_email=settings.FROM_EMAIL,
to_emails=sub.email,
subject='Newsletter Confirmation',
html_content='Thank you for signing up for my email newsletter! \
Please complete the process by \
<a href="{}/confirm/?email={}&conf_num={}"> clicking here to \
confirm your registration</a>.'.format(request.build_absolute_uri('/confirm/'),
sub.email,
sub.conf_num))
sg = SendGridAPIClient(settings.SENDGRID_API_KEY)
response = sg.send(message)
return render(request, 'sub.html', {'email': sub.email, 'action': 'added', 'form': SubscriberForm()})
else:
return render(request, 'sub.html', {'form': SubscriberForm()})
def confirm(request):
sub = Subscriber.objects.get(email=request.GET['email'])
if sub.conf_num == request.GET['conf_num']:
sub.confirmed = True
sub.save()
return render(request, 'sub.html', {'email': sub.email, 'action': 'confirmed'})
else:
return render(request, 'sub.html', {'email': sub.email, 'action': 'denied'})
def delete(request):
sub = Subscriber.objects.get(email=request.GET['email'])
if sub.conf_num == request.GET['conf_num']:
sub.delete()
return render(request, 'sub.html', {'email': sub.email, 'action': 'unsubscribed'})
else:
return render(request, 'sub.html', {'email': sub.email, 'action': 'denied'})
Код ошибки, который я получаю:
Traceback (most recent call last):
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\emman\Documents\Online%20Shop%20Website\ShoeWeb\home\views.py", line 108, in subscribe
sub.save()
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 746, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 784, in save_base
force_update, using, update_fields,
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 887, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 926, in _do_insert
using=using, raw=raw,
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1384, in execute_sql
cursor.execute(sql, params)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: home_subscriber.email
[09/Apr/2020 14:27:11] "POST /new/ HTTP/1.1" 500 154610
Internal Server Error: /new/
Traceback (most recent call last):
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\emman\Documents\Online%20Shop%20Website\ShoeWeb\home\views.py", line 120, in subscribe
response = sg.send(message)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\sendgrid\sendgrid.py", line 95, in send
response = self.client.mail.send.post(request_body=message.get())
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\python_http_client\client.py", line 262, in http_request
self._make_request(opener, request, timeout=timeout)
File "C:\Users\emman\AppData\Local\Programs\Python\Python37\lib\site-packages\python_http_client\client.py", line 178, in _make_request
raise exc
python_http_client.exceptions.UnauthorizedError: HTTP Error 401: Unauthorized
[09/Apr/2020 14:27:29] "POST /new/ HTTP/1.1" 500 122106