Answer the question
In order to leave comments, you need to log in
How to send letters with data to mail from the admin panel?
I extended the User class and you can create a user in the admin panel. Now I would like that when creating a user by the admin, all data is sent to him by mail. I know that this is very bad, but I would just like the password and login to come to the mail. here is my code.
models.py
class UserManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=UserManager.normalize_email(email),
username=username)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(email,
password=password,
username=username)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='Электропочта',
max_length=255,
unique=True,
db_index=True)
username = models.CharField(verbose_name='Ник', max_length=255, unique=True)
first_name = models.CharField(verbose_name='Имя', max_length=255, blank=True)
last_name = models.CharField(verbose_name='Фамилия', max_length=255, blank=True)
date_of_birth = models.DateField(verbose_name='День рождения', blank=True, null=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
def get_full_name(self):
return '%s %s' % (self.first_name, self.last_name,)
def get_short_name(self):
return self.username
def __unicode__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@property
def is_staff(self):
return self.is_admin
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email', 'username')
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("Passwords don't match")
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
class UserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()
class Meta:
model = User
def clean_password(self):
return self.initial["password"]
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from account.models import User
from account.forms import UserChangeForm, UserCreationForm
class UserAdmin(UserAdmin):
form = UserChangeForm
add_form = UserCreationForm
list_display = ('email', 'username', 'is_admin',)
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'username', 'password')}),
('Personal info', {'fields': ('date_of_birth', 'first_name', 'last_name')}),
('Permissions', {'fields': ('is_admin',)}),
('Important dates', {'fields': ('last_login',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'date_of_birth', 'password1', 'password2','first_name','last_name')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
admin.site.register(User, UserAdmin)
admin.site.unregister(Group)
Answer the question
In order to leave comments, you need to log in
ahhh, here the user wants to get the finished code, but does not want to read the docks....
registered in models.py
def create_user(self, email, username, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=UserManager.normalize_email(email),
username=username)
user.set_password(password)
send_mail('Subject here', 'Here is the message.', '[email protected]', ['[email protected]'], fail_silently=False)
user.save(using=self._db)
return user
ConnectionRefusedError: [WinError 10061] Подключение не установлено, т.к. конечн
ый компьютер отверг запрос на подключение
set up
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '******@gmail.com'
EMAIL_HOST_PASSWORD =*********'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
Do via signals: https://docs.djangoproject.com/en/1.6/topics/signals/
For example:
# signals.py
# -*- coding: utf-8 -*-
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.mail import send_mail
from django.contrib.auth import get_user_model
from django.conf import settings
User = get_user_model()
@receiver(post_save, sender=User)
def send_notification(sender, instance, created, **kwargs):
if created:
# здесь можно провести дополнительную фильтрацию, например if instance.is_admin и т.п.
send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, instance.email)
DEFAULT_FROM_EMAIL
the settings for sending mail.
typed in the command line
python -m smtpd -n -c DebuggingServer localhost:1025
error: uncaptured python exception, closing channel <__main__.DebuggingServer li
stening localhost:1025 at 0x1ea8850> (<class 'UnicodeEncodeError'>:'ascii' codec
can't encode characters in position 6-7: ordinal not in range(128) [C:\Python33
\lib\asyncore.py|read|83] [C:\Python33\lib\asyncore.py|handle_read_event|435] [C
:\Python33\lib\asyncore.py|handle_accept|512] [C:\Python33\lib\smtpd.py|handle_a
ccepted|600] [C:\Python33\lib\smtpd.py|__init__|148] [C:\Python33\lib\smtpd.py|p
ush|276])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question