Django форма отправляет почту дважды - PullRequest
0 голосов
/ 03 апреля 2020

при создании пользователя из Django панели администратора, я пытаюсь отправить письмо, которое было добавлено на сайт. Но почта запускается дважды. Ниже мой код

Models.py

class User(auth_models.AbstractBaseUser, auth_models.PermissionsMixin, TimestampedModel):
    email = models.EmailField(db_index=True, unique=True)
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    is_staff = models.BooleanField(default=False, help_text='Allow the user access to the admin site')
    is_superuser = models.BooleanField(
        default=False,
        help_text='User has all permissions'
    )
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    # force_password_change= models.BooleanField(default=True)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    objects = UserManager()

    def __unicode__(self):
        return self.email

    def __str__(self):
        if self.first_name == '' and self.last_name == '':
            return '{0}'.format(self.email)
        return '{0} ({1})'.format(self.get_full_name(), self.email)

    @property
    def token(self):
        return self._generate_jwt_token()

    def get_full_name(self):
        return "{0} {1}".format(self.first_name, self.last_name)

    def get_short_name(self):
        return self.first_name

    def _generate_jwt_token(self):

        dt = datetime.now() + timedelta(days=60)

        token = jwt.encode({
            'id': self.pk,
            'exp': int(dt.strftime('%s'))
        }, settings.SECRET_KEY, algorithm='HS256')

        return token.decode('utf-8')

    def generate_password(self):
        password = User.objects.make_random_password()
        self.set_password(password)
        self.save()
        return password

    class Meta:
        verbose_name="Site Admin"
        verbose_name_plural= 'Site Admins'

Forms.py

class UserCreationForm(forms.ModelForm):
    error_messages = {
        'password_mismatch': "The two password fields didn't match.",
    }
    email= forms.EmailField(max_length=50, help_text="Required")
    password1 = forms.CharField(label="Password", widget=forms.PasswordInput)
    password2 = forms.CharField(
        label="Password confirmation",
        widget=forms.PasswordInput,
        help_text="Enter the same password as above, for verification."
    )

    class Meta:
        model = User
        fields = ('email', 'password1','password2')

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        return password2


    def save(self, commit=True):

        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

    @receiver(post_save, sender=User)
    def send_user_data_when_created_by_admin(sender, instance, **kwargs):
        email = instance.email
        password= instance.password
        current_site= get_current_site(instance)
        # print(current_site)
        token= account_activation_token.make_token(user=User)
        if instance.last_login is None:
            html_content = "You have been added to the Admin Site"
                       "your username:%s <br> password:%s <br>"
            message = EmailMessage(subject='Please access your content', body=html_content % (email, password), to=[email])
            message.content_subtype = 'html'
            message.send()
        else:
            pass

settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'xyz@gmail.com'
EMAIL_HOST_PASSWORD = 'XXXXXX'
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL= 'xyz@gmail.com'

Я пытаюсь создать пользователя и отправить письмо для активации его учетной записи. В качестве первого шага я пытаюсь отправить письмо, которое работает, но письмо отправляется дважды пользователю

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