отправить подтверждение по электронной почте с помощью sendgrid через django - PullRequest
2 голосов
/ 11 апреля 2020

view.py class Registration (TemplateView): template_name = 'sign_up. html'

def get(self, request, *args, **kwargs):
    Form = Sign_up()
    return render(request, self.template_name, {'form': Form})

def post(self, request):
    data = self.request.POST.get
    try:
        user = User(
            first_name=data('first_name'),
            last_name=data('last_name'),
            email=data('email'),
            username=data('username'),
        )
        user.set_password(data('password').strip())
        user.is_active = False
        user.save()
        request.session['SESSION_KEY'] = user.id

        try:
            sg = SendGridAPIClient(api_key=settings.SENDGRID_API_KEY)
            from_email = "commerce@gmail.com"
            to_email = "usmanimtiaz9991@gmail.com"
            subject = "Sending with SendGrid is Fun"
            content = Content("text/plain", "and easy to do anywhere, even with Python")
            mail = Mail(from_email, subject, to_email, content)
            response = sg.client.mail.send.post(request_body=mail.get())
            messages.add_message(request, messages.SUCCESS, response.status_code, response.body, response.headers)
            return HttpResponse('done')
        except Exception as c:
            return HttpResponse('failed:{}'.format(c), 500)
    except Exception as e:
        return HttpResponse('failed {}'.format(e), 500)

class ActivateAccount (View):

def get(self, request, uidb64, token, *args, **kwargs):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.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.profile.email_confirmed = True
        user.save()
        login(request, user)
        messages.success(request, 'Your account have been confirmed.')
        return redirect('home')
    else:
        messages.warning(request, 'The confirmation link was invalid, possibly because it has already been used.')
        return redirect('home')

Models.py

из django .db импорт моделей

из django .contrib.auth.models import Пользователь

из django .db.models.signals import post_save

из django .dispatch импорт получателя

Профиль класса (модели. Модель):

user = models.OneToOneField(User, on_delete=models.CASCADE)

email_confirmed = models.BooleanField(default=False)

@ получатель (post_save, отправитель = пользователь)

def update_user_profile (отправитель, экземпляр, создан, ** kwargs):

if created:

    Profile.objects.create(user=instance)

    instance.profile.save()

settings.py

EMAIL_BACKEND = "sgbackend.SendGridBackend"

SENDGRID_API_KEY = 'apikey'

EMAIL_HOST = 'smtp.sendgrid. net'

EMAIL_HOST_USER = 'apikey'

EMAIL_HOST_PASSWORD = SENDGRID_API_KEY

EMAIL_P37

1037 * 1037 = 1037 * 1037 = 1037 * 1037 = 1037 * 1037 = 1037 * 1037 = 1037 *1037* 1037 *1037* 1037 *1037* 1037 *1037* 1037 *1037* 1037 *1037* 1037 *1037* 1037 *1037* 1037 *1037* E37IL 1038 * EMAIL_USE_TLS = True

Функция «Моя регистрация» работает правильно, отображается ошибка HTTP Ошибка 400: Неверный запрос

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...