简体   繁体   中英

Django - How to make a notification?f when User Register It will send notification to Email of Admin

class SignupForm(forms.Form):
    username = forms.CharField(max_length=10, widget=forms.TextInput({
                'class': 'form-control',
                'placeholder': 'Username',
                })
            )
    email = forms.EmailField(
            max_length=200,
            widget=forms.TextInput({
                'class': 'form-control',
                'placeholder': 'Email'
                })
            )
    password = forms.CharField(
            min_length=6, max_length=10,
            widget=forms.PasswordInput({
                'class': 'form-control',
                'placeholder': 'Password'
                })
            )

    repeat_password = forms.CharField(
            min_length=6, max_length=10,
            widget=forms.PasswordInput({
                'class': 'form-control',
                'placeholder': 'Repeat password'
                })
            )

Here is my form.py, how to make an email notification to the email of server? That will notify the admin that there is a new User register to his application.

Django implements mail_admins() which is configured by the ADMINS setting, as can be found in thedocumentation .

Basic Usage

from django.core.mail import mail_admins

mail_admins(
    'Subject here',
    'Here is the message.',
    fail_silently=False
)

First thing is you need to use ModelForm instead of forms.Form See this post to see the difference of ModelForm and Form on detail.

class SignupForm(forms.ModelForm):
    
     .....
     class Meta:
        model = YourUserModel
        fields = [...]

Now from the view you can send email to the site admin like this after new user account created.

 form = SignupForm(request.POST)
    if form.is_valid():
       user = form.save()
       # now you can send mail to the site admin
       mail_admins('subject','message')

See the docshere for sending email

Another option is to set a pre_save signal on user that will trigger one's user is created:

models.py

from django.db.models.signals import pre_save

@receiver(pre_save, sender=User)
def user_created_email_notification(sender, instance, *args, **kwargs):
    if instance.id:
         mail_admins('subject','message')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM