i currently try the implement my very own user model. Therefor i created a new app "accounts". But each time when i try to create anew user i get the following error:
AttributeError: 'AnonymousUser' object has no attribute '_meta'
accounts - models.py:
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
#User Model Manager
class UserManager(BaseUserManager):
def create_user(self, username, password=None):
"""
Creates and saves a User with the given username and password.
"""
if not username:
raise ValueError('Error: The User you want to create must have an username, try again')
user = self.model(
user=self.normalize_username(username),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, username, password):
"""
Creates and saves a staff user with the given username and password.
"""
user = self.create_user(
username,
password=password,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, username, password):
"""
Creates and saves a superuser with the given username and password.
"""
user = self.create_user(
username,
password=password,
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
#User fields
user = models.CharField(verbose_name='username',max_length=30,unique=True)
bio = models.TextField(max_length=5000, blank=True, null=True)
pubpgp = models.TextField(blank=True, null=True)
#Account typs
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
# notice the absence of a "Password field", that's built in.
USERNAME_FIELD = 'user'
REQUIRED_FIELDS = [] # Username & Password are required by default.
def get_full_name(self):
# The user is identified by their Username ;)
return self.user
def get_short_name(self):
# The user is identified by their Username address
return self.user
def __str__(self):
return self.user
def has_perm(self, perm, obj=None):
"""Does the user have a specific permission?"""
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"""Does the user have permissions to view the app `app_label`?"""
# Simplest possible answer: Yes, always
return True
#property
def is_staff(self):
"""Is the user a member of staff?"""
return self.staff
#property
def is_admin(self):
"""Is the user a admin member?"""
return self.admin
#property
def is_active(self):
"""Is the user active?"""
return self.active
objects = UserManager()
After that i jumpt back to settings.py and added the custom user model to my acctual blog application:
AUTH_USER_MODEL = 'accounts.User'
and i also added
INSTALLED_APPS = [
...
'accounts',
...
]
All this user model/django stuff is a bit new to me and i have no idea what the error "AttributeError: 'Manager' object has no attribute 'get_by_natural_key'" means.
Thanks :D
Edit: AttributeError: 'UserManager' object has no attribute 'normalize_username'
normalize_username belongs to AbstractBaseUser, you can try the code below.
In signup view, when you save the form you already get the user (form.save()). Because the reason from authentication is to verify a set of credentials and getting the user (but we already have the user)
In this line: user = authenticate(username=username, password=raw_password), the authenticate method takes request as the first argument, so it should be: user = authenticate(request, username=username, password=raw_password), therefore you got the Error 'AnonymousUser' object has no attribute '_meta'.
Try:
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('post_list')
Edit UserManager:
Reaname all created users to some other name (ex. my_user) because you have tow varibales with the same name (the USERNAME_FIELD and the user created)
Here is the signature of create_user and create_superuser
create_user(*username_field*, password=None, **other_fields)
create_superuser(*username_field*, password, **other_fields)
They take the USERNAME_FIELD as the first argument, and yours is user
class UserManager(BaseUserManager):
def create_user(self, user, password=None):
"""
Creates and saves a User with the given username and password.
"""
if not user:
raise ValueError('Error: The User you want to create must have an username, try again')
my_user = self.model(
user=self.model.normalize_username(user),
)
my_user.set_password(password)
my_user.save(using=self._db)
return my_user
def create_staffuser(self, user, password):
"""
Creates and saves a staff user with the given username and password.
"""
my_user = self.create_user(
user,
password=password,
)
my_user.staff = True
my_user.save(using=self._db)
return my_user
def create_superuser(self, user, password):
"""
Creates and saves a superuser with the given username and password.
"""
my_user = self.create_user(
user,
password=password,
)
my_user.staff = True
my_user.admin = True
my_user.save(using=self._db)
return my_user
I hope this will help.
Related
So I've customized user using the AbstractUser and then inherited two users from my custom user. The signup works just fine and registers my users. However I'm having trouble creating login logic that looks in all 2 models to find the credentials and then takes user to their respective dashboard.
Here is my models.py:
class User(AbstractUser):
is_doc = models.BooleanField(default=False)
is_patient = models.BooleanField(default=False)
objects = UserManager()
class Patient(User):
address = models.CharField(max_length=210)
def __str__(self):
return self.first_name + " " + self.last_name
class Doctor(User):
address = models.CharField(max_length=210)
def __str__(self):
return self.first_name
managers.py:
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
if email is None:
raise TypeError('Users must have an email address.')
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.save()
return user
def create_patient(self, email, password):
if password is None:
raise TypeError('Must have a password')
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.is_patient = True
user.save()
def create_superuser(self, email, password):
if password is None:
raise TypeError('Superusers must have a password.')
user = self.create_user(email, password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
views.py:
def patient_signup(request):
if request.method == 'POST':
form = forms.PatientSignUpForm(request.POST)
if form.is_valid():
models.Patient.objects.create(**form.cleaned_data)
return redirect('')
else:
form = forms.PatientSignUpForm(initial={'is_patient': True})
return render(request, 'patient_signup.html', {'form': form})
The default authentication using django.contrib.auth does not work and just redirects the same login page again (tried following the docs). So I don't have a login view logic now. How would I login my users and determine is_patient or is_doctor?
I create a custom model for User, By this I can create superuser from command line, and its create successfully. But when I trying to login to Django admin with created Super user its show me This error
#property
def is_staff(self):
return self.staff
#property
def is_superuser(self):
return self.superuser
#property
def is_active(self):
return self.active
These property also set True
models.py
from django.db import models
from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser)
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
"""
creates a user with given email and password
"""
if not email:
raise ValueError('user must have a email address')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(self._db)
return user
def create_staffuser(self, email, password):
"""
creates a user with staff permissions
"""
user = self.create_user(
email=email,
password=password
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""
creates a superuser with email and password
"""
user = self.create_user(
email=email,
password=password
)
user.staff = True
user.superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='Email address',
max_length=255,
unique=True
)
active = models.BooleanField(default=False)
staff = models.BooleanField(default=False) # <- admin user, not super user
superuser = models.BooleanField(default=False) # <- super user
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = [] # <- email and password are required by default
class Meta:
app_label = "account_app"
db_table = "users"
def __str__(self):
return self.email
def get_full_name(self):
return str(self.email)
def has_perm(self, perm, obj=None):
"""Does the user has a specific permission"""
return True
def has_module_perms(self, app_lable):
"""Does the user has permission to view a specific app"""
return True
#property
def is_staff(self):
"""Is the user a staff member"""
return self.staff
#property
def is_superuser(self):
"""Is the user a admin member"""
return self.superuser
#property
def is_active(self):
"""Is the user active"""
return self.active
# hook the user manager to objects
objects = UserManager()
settings.py where I change for Custom User Model
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dashboard_app',
'account_app',
]
AUTH_USER_MODEL = "account_app.User" # changes the built-in user model to ours
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
WSGI_APPLICATION = 'SMSystem.wsgi.application'
its set default value for active = 0 need to set 1 or True
Had the same issue. Instead of password=None, change it to password. And pass 'password=password' together with 'username=username' into the create_user function as you see below:
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, password):
if not email:
raise ValueError('Please add an email address')
if not username:
raise ValueError('Please add an username')
**user = self.model(email=self.normalize_email(
email), username=username, password=password)**
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(email=self.normalize_email(
email), username=username, password=password)
user.is_active = True
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
Hope it works for you
Only users with is_active attribute True can log into the system.
Inside createuser method pass active=True or change default value of active to True
def create_user(self, email, password=None):
"""
creates a user with given email and password
"""
if not email:
raise ValueError('user must have a email address')
user = self.model(
email=self.normalize_email(email),
active=True, #Add this line
)
user.set_password(password)
user.save(self._db)
return user
--OR, change default value of active to true --
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='Email address',
max_length=255,
unique=True
)
# change default value to True
active = models.BooleanField(default=True)
i am creating custom user model in django using abstract base user class, i want to create user with only two fields "phone and password " and name being the optional field , which i have set in my models .py that blank =true. i have created a rest api for user registration using my custom user model, but every time i try to create new user with phone and password it gives me below error:-
IntegrityError at /api/users/
UNIQUE constraint failed: accounts_user.name
Request Method: POST
Request URL: http://127.0.0.1:8000/api/users/
Django Version: 3.0.1
Exception Type: IntegrityError
Exception Value:
UNIQUE constraint failed: accounts_user.name
Exception Location: /usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 396
Python Executable: /usr/local/opt/python/bin/python3.7
Python Version: 3.7.6
Python Path:
['/Users/raghav/milkbasketdemo/milkbasketdemo',
'/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
'/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
'/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
'/usr/local/lib/python3.7/site-packages']
Please help where i am going wrong , i have searched and tried changing code number of times but nothing is working for me.
please find the below code of models.py
class UserManager(BaseUserManager):
def create_user(self,phone, password=None,is_staff=False,is_admin=False,is_active=True):
if phone is None:
raise TypeError('Users must have a phonenumber.')
user = self.model(phone=phone)
user.set_password(password)
user.staff=is_staff
user.admin=is_admin
user.active=is_active
user.save(using=self._db)
return user
def create_staffuser(self, phone, password):
"""
Creates and saves a staff user with the given email and password.
"""
user = self.create_user(
phone,
password=password,
is_staff=True
)
# user.staff = True
user.save(using=self._db)
return users
def create_superuser(self, phone, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(
phone=phone,
password=password,
is_staff=True,
is_admin=True
)
#user.staff = True
#user.admin = True
#user.active=True
user.save(using=self._db)
return user
class User(AbstractBaseUser,PermissionsMixin):
phone_regex=RegexValidator(regex = r'^[6-9]\d{9}$',message='please enter the correct phonenumber')
#name_regex=RegexValidator(regex=r'/^[A-Za-z]+$/',message='Please enter the correct name')
phone=models.CharField(validators=[phone_regex],max_length=15,unique=True)
name=models.CharField(max_length=15,unique=True,blank=True)
date_joined=models.DateTimeField(verbose_name='date joined',auto_now_add=True)
last_login=models.DateTimeField(verbose_name='last login',auto_now=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False)
first_login=models.BooleanField(default=False)
USERNAME_FIELD='phone'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return self.phone
#property
def token(self):
return self._generate_jwt_token()
def get_full_name(self):
return self.name
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
Below is code of serializer.py
class RegistrationSerializer(serializers.ModelSerializer):
password = serializers.CharField(
max_length=128,
min_length=8,
write_only=True
)
token = serializers.CharField(max_length=255, read_only=True)
class Meta:
fields = ['phone', 'password']
def create(self, validated_data):
return User.objects.create_user(**validated_data)
I'm extending AbstractBaseUser with my custom user model. I can create a superuser via shell successfully with the UserManager() below which is created in the database correctly.
For testing, I've created a superuser with the username test & password of test.
check_password()
def set_password(self, raw_password):
self.password = make_password(raw_password)
self._password = raw_password
def check_password(self, raw_password):
"""
Return a boolean of whether the raw_password was correct. Handles
hashing formats behind the scenes.
"""
def setter(raw_password):
self.set_password(raw_password)
# Password hash upgrades shouldn't be considered password changes.
self._password = None
self.save(update_fields=["password"])
return check_password(raw_password, self.password, setter)
I can run this test user against the check_password("test", "test") method which returns True as expected, but if I try to login via /admin I get "Password Incorrect" with a 200 status code on the POST.
Update: check_password does return False when given the raw password & hash
>>> u = User.objects.get(pk=1)
>>> u.check_password('test')
False
>>> u.check_password('pbkdf2_sha256$150000$sWSs4Yj3gQe1$75A2JmFurNX2oOeKJ18TvsB2G3YU6mYjIuHlaH7i6/k=')
False
Relevant app versions
Django==2.2.3
djangorestframework==3.10.1
User Model
class User(AbstractBaseUser):
USERNAME_FIELD = ('username')
REQUIRED_FIELDS = ('email', 'password')
username = models.CharField(max_length=15, unique=True)
twitch_id = models.IntegerField(null=True)
avatar = models.URLField(null=True, blank=True)
is_live = models.BooleanField(default=False)
email = models.EmailField(unique=True)
password = models.CharField(max_length=50, default="password")
register_date = models.DateTimeField(auto_now=True)
twitch_token = models.ForeignKey(TwitchToken, on_delete=models.SET_NULL, null=True)
twitter_token = models.ForeignKey(TwitterToken, on_delete=models.SET_NULL, null=True)
# attempted giving flags from original User model
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
objects = UserManager()
class Meta:
db_table = 'users_user'
def __str__(self):
return self.username
"""
Properties are redundant with flags above
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.active
#property
def is_staff(self):
return self.staff
#property
def is_superuser(self):
return self.superuser
"""
UserManager()
class UserManager(BaseUserManager):
def create_user(self, username, email, password):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, username, email, password):
"""
Creates and saves a staff user with the given email and password.
"""
user = self.create_user(
username,
email,
password,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, username, email, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(
username,
email,
password,
)
user.is_staff = True
user.is_admin = True
user.is_active = True
user.save(using=self._db)
return user
I am explicitly stating to use django.contrib.auth.backends.ModelBackend (default) in my settings & my AUTH_USER_MODEL is set. (I have seen some use a tuple & others use a list. I've tried both, same results)
AUTH_USER_MODEL = 'users.User'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
I suspect I'm not even hitting ModelBackend 'cause I've put some prints in the authenticate() method that aren't running, as well I have deleted the entire file & see the same results. So I suspect the issue is somewhere between Django's determination of the auth user model & actually attempting authentication.
I've looked through countless SO posts & forum posts and I'm not seeing any step of the extension process that I'm missing, but I can't get anything valuable from stack traces either.
Django ModelBackend for Reference
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
UserModel = get_user_model()
class ModelBackend:
"""
Authenticates against settings.AUTH_USER_MODEL.
"""
def authenticate(self, request, username=None, password=None, **kwargs):
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a nonexistent user (#20760).
UserModel().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user
def user_can_authenticate(self, user):
"""
Reject users with is_active=False. Custom user models that don't have
that attribute are allowed.
"""
is_active = getattr(user, True, None)
return is_active or is_active is None
def _get_user_permissions(self, user_obj):
return user_obj.user_permissions.all()
def _get_group_permissions(self, user_obj):
user_groups_field = get_user_model()._meta.get_field('groups')
user_groups_query = 'group__%s' % user_groups_field.related_query_name()
return Permission.objects.filter(**{user_groups_query: user_obj})
def _get_permissions(self, user_obj, obj, from_name):
"""
Return the permissions of `user_obj` from `from_name`. `from_name` can
be either "group" or "user" to return permissions from
`_get_group_permissions` or `_get_user_permissions` respectively.
"""
if not user_obj.is_active or user_obj.is_anonymous or obj is not None:
return set()
perm_cache_name = '_%s_perm_cache' % from_name
if not hasattr(user_obj, perm_cache_name):
if user_obj.is_superuser:
perms = Permission.objects.all()
else:
perms = getattr(self, '_get_%s_permissions' % from_name)(user_obj)
perms = perms.values_list('content_type__app_label', 'codename').order_by()
setattr(user_obj, perm_cache_name, {"%s.%s" % (ct, name) for ct, name in perms})
return getattr(user_obj, perm_cache_name)
def get_user_permissions(self, user_obj, obj=None):
"""
Return a set of permission strings the user `user_obj` has from their
`user_permissions`.
"""
return self._get_permissions(user_obj, obj, 'user')
def get_group_permissions(self, user_obj, obj=None):
"""
Return a set of permission strings the user `user_obj` has from the
groups they belong.
"""
return self._get_permissions(user_obj, obj, 'group')
def get_all_permissions(self, user_obj, obj=None):
if not user_obj.is_active or user_obj.is_anonymous or obj is not None:
return set()
if not hasattr(user_obj, '_perm_cache'):
user_obj._perm_cache = {
*self.get_user_permissions(user_obj),
*self.get_group_permissions(user_obj),
}
return user_obj._perm_cache
def has_perm(self, user_obj, perm, obj=None):
return user_obj.is_active and perm in self.get_all_permissions(user_obj, obj)
def has_module_perms(self, user_obj, app_label):
"""
Return True if user_obj has any permissions in the given app_label.
"""
return user_obj.is_active and any(
perm[:perm.index('.')] == app_label
for perm in self.get_all_permissions(user_obj)
)
def get_user(self, user_id):
try:
user = UserModel._default_manager.get(pk=user_id)
except UserModel.DoesNotExist:
return None
return user if self.user_can_authenticate(user) else None
class AllowAllUsersModelBackend(ModelBackend):
def user_can_authenticate(self, user):
return True
class RemoteUserBackend(ModelBackend):
"""
This backend is to be used in conjunction with the ``RemoteUserMiddleware``
found in the middleware module of this package, and is used when the server
is handling authentication outside of Django.
By default, the ``authenticate`` method creates ``User`` objects for
usernames that don't already exist in the database. Subclasses can disable
this behavior by setting the ``create_unknown_user`` attribute to
``False``.
"""
# Create a User object if not already in the database?
create_unknown_user = True
def authenticate(self, request, remote_user):
"""
The username passed as ``remote_user`` is considered trusted. Return
the ``User`` object with the given username. Create a new ``User``
object if ``create_unknown_user`` is ``True``.
Return None if ``create_unknown_user`` is ``False`` and a ``User``
object with the given username is not found in the database.
"""
if not remote_user:
return
user = None
username = self.clean_username(remote_user)
# Note that this could be accomplished in one try-except clause, but
# instead we use get_or_create when creating unknown users since it has
# built-in safeguards for multiple threads.
if self.create_unknown_user:
user, created = UserModel._default_manager.get_or_create(**{
UserModel.USERNAME_FIELD: username
})
if created:
user = self.configure_user(user)
else:
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
pass
return user if self.user_can_authenticate(user) else None
def clean_username(self, username):
"""
Perform any cleaning on the "username" prior to using it to get or
create the user object. Return the cleaned username.
By default, return the username unchanged.
"""
return username
def configure_user(self, user):
"""
Configure a user after creation and return the updated user.
By default, return the user unmodified.
"""
return user
class AllowAllUsersRemoteUserBackend(RemoteUserBackend):
def user_can_authenticate(self, user):
return True
The ModelBackend.authenticate method first gets the user object from the database using the get_by_natural_key method of the user models default manager, if this fails then authentication will fail
def get_by_natural_key(self, username):
return self.get(**{self.model.USERNAME_FIELD: username})
Because your create_user method is not setting the username field correctly this is failing
The reason why you were able to create the user even though the username field is required is probably because you are using MySQL and running in non-strict mode in which case null values will be converted to empty strings
What was done
I have a custom User model called MyUser as it is described in an full example for an custom user model on the docs and a so called UserProfile that is connected to MyUser by an One-to-one relationship like it's described in the Django documentation about how to extend an existing user model.
In the documentation for Customizing authentication is an example for how to connect a post_save signal with the existing User model.
By following this, I put an testing receiver in a signals.py that is loaded by my apps.py file, like it's described in this SO answer.
Configuration
signal.py
def post_save_receiver(sender, instance, created, **kwargs):
send_mail('Testing', "Just testing...", 'hell#earth.tld', ['admin#heaven.tld'], fail_silently=False)
post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL)
models.py
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(email,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __str__(self): # __unicode__ on Python 2
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
#property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
views.py
def UserLogin(request):
if request.user.is_authenticated():
return HttpResponseRedirect("http://www.heaven.tld/account")
else:
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request, user)
return HttpResponseRedirect("http://www.heaven.tld/account")
else:
error_msg = 'Please try again!'
return render(request, "development",
{'form':form,
'error_msg':error_msg,
})
else:
error_msg = "Please try again!"
return render(request, "development",
{'form':form,
'error_msg':error_msg,
})
else:
form = UserLoginForm()
return render(request, "development", {'form': form})
The Problem
Now if I log in I always get this mail, but I want it only if a user was created.
Logging in causes the last_login timestamp to be updated, which triggers a save.
As others have stated, you just need to use the created parameter, which your signal receives but you currently ignore.
try:
def post_save_receiver(sender, instance, created, **kwargs):
if created:
send_mail('Testing', "Just testing...", 'hell#earth.tld', ['admin#heaven.tld'], fail_silently=False)
post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL)
I can't understand what will be saved when you login. You can use ipdb to trace it. By the way, if you set the created condition before send_mail function, the problem should be resolved.
if created:
send_mail(...)