user = get_user_model().objects.create_user(email,password) - django

I am getting this error while executing .I have made a test models file to test my models using TDD.I could find the error i have also tried models.User.create_user but that also didnt work.
Here is my test_models.py
'''
class ModelTests(TestCase):
def test_create_user_with_email_successful(self):
"""Test creating a new user with email"""
email = 'hassansahi6464#gmail.com'
password = 'admin'
user = get_user_model().objects.create_user(
email=email,
password=password
)
self.assertEqual(user.email, email)
self.assertTrue(user.check_password(password))
def test_new_user_email_normalized(self):
"""Test the email for user is normalized"""
email = 'hassansahi6464#GMAIL.COM'
user = get_user_model().objects.create_user(email,'admin')
self.assertEqual(user.email,email.lower())
and here is my models
from django.db import models
from django.contrib.auth.models import UserManager , AbstractBaseUser , BaseUserManager , PermissionsMixin
from django.db.models.base import Model
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
user = self.model(email=self.normalize_email(email) , **extra_fields)
user.set_password(password)
user.save(using = self._db)
return user
class User(AbstractBaseUser,PermissionsMixin,Model):
email = models.EmailField(max_length=100,unique=True)
name = models.CharField(max_length=150)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager
USERNAME_FIELD = 'email'
Settings.py
AUTH_USER_MODEL = 'core.User'

Solved The problem by simply changing UserManager to UserManager() in models.py
objects = UserManager()

Related

Exception Value: 'CustomUser' object is not callable | CustomUserModel

I am trying to create a custom user model. The model is working fine in command prompt and I am able to login to admin panel as well. I can access Login page as well. But when I try to access the SignUp page Is is showing me the following error.
Error image
models.py
from django.db import models
from django.contrib import auth
from django.urls import reverse
# Create your models here.
# for custom user
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, User
from .managers import CustomUserManager
class CustomUser(AbstractBaseUser, PermissionsMixin):
'''Model representation for user'''
user_type_choices = (
('ps','problem_solver'),
('pp','problem_provider')
)
account_type_choices = (
('o','Organization'),
('i','Individual')
)
user_type = models.CharField(max_length=5, choices=user_type_choices, default='pp', verbose_name="Who you are? ")
account_type = models.CharField(max_length=5, choices= account_type_choices, default='o', verbose_name="Account Type ")
email = models.EmailField(max_length=50, unique=True, blank=False, verbose_name="Your Email ")
is_active = models.BooleanField(default=True) # anyone who signs up for thsi application is by default an active user
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False) # the person who has highest level of control over database
# need to specify manager class for this user
objects = CustomUserManager()
# we are not placing password field here because the password field will always be required
REQUIRED_FIELDS = ['user_type', 'account_type']
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
# class User(User, PermissionsMixin): # for username and password
# def __str__(self):
# return "#{}".format(self.username)
# def get_absolute_url(self):
# return reverse("Solver_detail", kwargs={"pk": self.pk})
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from . import forms
from django.views.generic import CreateView
from .managers import CustomUserManager
# Create your views here.
class SignUpView(CreateView):
form_class = forms.SignUpForm
success_url = reverse_lazy('login')
template_name = 'accounts/signup.html'
managers.py
from django.contrib.auth.models import BaseUserManager
# from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
class CustomUserManager(BaseUserManager):
def create_user(self, user_type, account_type, email, password):
if not email:
raise ValueError('User must provide valis email address')
if not password:
raise ValueError('User must provide password')
user = self.model(
user_type = user_type,
account_type = account_type,
email = self.normalize_email(email=email) # it normalizes the email for storage
)
user.set_password(raw_password = password) # it hashes password before setting it up into the database
user.save(using = self._db)
return user
def create_superuser(self, user_type, account_type, email, password):
user = self.create_user(
user_type= user_type,
account_type= account_type,
email=email,
password= password
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using = self._db)
return user
forms.py
# from django.contrib.auth import get_user_model
from accounts.models import CustomUser
from django.contrib.auth.forms import UserCreationForm
class SignUpForm(UserCreationForm):
class Meta:
fields = ('user_type','account_type','email', 'password1', 'password2')
model = CustomUser()
# def __init__(self, *args, **kwargs) -> None:
# super().__init__(*args, **kwargs)
admin.py
from django.contrib import admin
from accounts.models import CustomUser
# Register your models here.
admin.site.register(CustomUser)
I am newbie to django developement. Please help me out.
I am expecting to know how to resolve this kind of error
your wrong in file:
class SignUpForm(UserCreationForm):
class Meta:
fields = ('user_type','account_type','email', 'password1', 'password2')
model = CustomUser()
Fix to
class SignUpForm(forms.ModelForm):
class Meta:
fields = ('user_type','account_type','email', 'password1', 'password2')
model = CustomUser
Because model required one MODEL, you write CustomUser() mean callable object. Model CustomUser can't do it and raise exception

CustomAccounManager.create_user() missing 1 required positional argument: 'email'

I am trying creating a custom user model in django - which I am using as a backend. On django admin I can create users without issue. My problem arises when I try to register a new account via postman.
In postman I have the email field filled out in the body, yet I still get the error missing 1 required positional argument: 'email'.
models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.utils.translation import gettext_lazy as _
class CustomAccounManager(BaseUserManager):
def create_superuser(self, email, username, password, **other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_active', True)
return self.create_user(self, email, username, password, **other_fields)
def create_user(self, email, username, password, **other_fields):
if not email:
raise ValueError(_('You must provide an email address'))
email = self.normalize_email(email)
user = self.model(email=email, username=username, **other_fields)
user.set_password(password)
user.save()
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
username = models.CharField(max_length=150, unique = True)
is_student = models.BooleanField(default=False)
is_teacher = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
objects = CustomAccounManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __str__(self):
return self.username
serializers.py
from rest_framework import serializers
from rest_framework.authtoken.models import Token
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'password')
extra_kwargs = {'password': {'write_only': True, 'required': False}}
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
Token.objects.create(user=user)
return user
views.py
from rest_framework import viewsets
from django.shortcuts import render
from .models import User
from .serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset =User.objects.all()
serializer_class = UserSerializer
Any help is appreciated!
This is because you are making USERNAME_FIELD = 'email' in your custom user model, so you have to set USERNAME_FIELD = 'username' and in the email field, set
email = models.EmailField(_('email address'), null=True, blank=True)
but if you need the USERNAME_FIELD = 'email' you have to send it with other data, it's based on your case.

Please enter the correct Email and password for a staff account. Note that both fields may be case-sensitive

I complete makemigrations and migrate then create a superuser. After this
http://127.0.0.1:8000/admin i try to log in then show this error
Please enter the correct Email and password for a staff account. Note that both fields may be case-sensitive
seetings.py
AUTH_USER_MODEL = 'user.CustomUser'
**models.py**
from django.db import models
from django.contrib.auth.models import AbstractUser,BaseUserManager
class CustomUserManager(BaseUserManager):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
def create_user(self, email, password=None):
if not email:
raise ValueError('User must have an email id')
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=None):
user=self.create_user(
email,
password=password
)
user.is_admin = True
user.save(using=self._db)
return user
class CustomUser(AbstractUser):
#only add email field for login
email = models.EmailField(
verbose_name='Email',
max_length=50,
unique=True
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = CustomUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def __str__(self):
return self.email
***admin.py***
from django.contrib import admin
from django.contrib.auth import get_user_model
user=get_user_model()
admin.site.register(user)
i had this problem.
you should define is_staff=True in create_superuser function and you should pass **kwargs as argument in this function.
i hope your problem solve.

How to fix "TypeError: argument of type 'ConnectionHandler' is not iterable" when running a django test?

When I do ```python -m unittest`` inside of my users app, I get this error:
TypeError: argument of type 'ConnectionHandler' is not iterable
I was customizing my User model in django and I wanted to make a test for it. I already did the migrations and the custom User model works good (I did with a new database), so I expected to run the test successfully. Here is my test code:
from django.test import TestCase
from django.contrib.auth import get_user_model
# Create your tests here.
class UsersManagersTests(TestCase):
def test_create_user(self):
User = get_user_model()
user = User.objects.create_user(email='normal#user.com', password='foo')
self.assertEqual(user.email, 'normal#user.com')
self.assertTrue(user.is_active)
self.assertFalse(user.is_staff)
self.assertFalse(user.is_superuser)
try:
# username is None for the AbstractUser option
# username does not exist for the AbstractBaseUser option
self.assertIsNone(user.username)
except AttributeError:
pass
with self.assertRaises(TypeError):
User.objects.create_user()
with self.assertRaises(TypeError):
User.objects.create_user(email='')
with self.assertRaises(ValueError):
User.objects.create_user(email='', password="foo")
def test_create_superuser(self):
User = get_user_model()
admin_user = User.objects.create_superuser('super#user.com', 'foo')
self.assertEqual(admin_user.email, 'super#user.com')
self.assertTrue(admin_user.is_active)
self.assertTrue(admin_user.is_staff)
self.assertTrue(admin_user.is_superuser)
try:
# username is None for the AbstractUser option
# username does not exist for the AbstractBaseUser option
self.assertIsNone(admin_user.username)
except AttributeError:
pass
with self.assertRaises(ValueError):
User.objects.create_superuser(
email='super#user.com', password='foo', is_superuser=False)
settings.py
AUTH_USER_MODEL = 'users.CustomUser'
models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
from .managers import CustomUserManager
# Create your models here.
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_deleted = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
updated_date=models.DateTimeField(auto_now=True)
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
('O', 'Others'),
)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
managers.py
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
class CustomUserManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers
for authentication instead of usernames.
"""
def create_user(self, email, password, **extra_fields):
"""
Create and save a User with the given email and password.
"""
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
"""
Create and save a SuperUser with the given email and password.
"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(_('Superuser must have is_staff=True.'))
if extra_fields.get('is_superuser') is not True:
raise ValueError(_('Superuser must have is_superuser=True.'))
return self.create_user(email, password, **extra_fields)
Why does the test fail?
The error is probably due to the configuration of your IDE.
What happens when you run "python manage.py test" ?

OAuth2 custom basic user model

I am using rest_framework_social_oauth2
I want to make a minimum change in oauth.User. Search to exchange AbstractBaseUser by AbstractUser and add PermissionMixin. But nothing works.
My app> models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser, PermissionsMixin, UserManager
class MyUser(AbstractUser, PermissionsMixin):
country_code = models.CharField(max_length=10, blank=True)
objects = UserManager()
My settings.py:
AUTH_USER_MODEL ='userTest.MyUser'
As indicated by tutorials, not did makemigrations and migrate.
ERRO:
File "/Users/luisdemarchi/Git/django/.env/lib/python3.5/site-packages/django/db/models/manager.py", line 277, in get
self.model._meta.swapped,
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'userTest.MyUser'
We managed. I'll put here a complete example for those who want to make an improvement in OAuth2.user. In our case we created the username automatically.
PS: Need create class AuthManager()
userTest(myApp) > models.py
import uuid as uuid
from django.contrib.auth.models import BaseUserManager, AbstractUser
from django.db import models
from rest_framework import exceptions
class AuthManager(BaseUserManager):
def create_user(self, email, username=None, password=None):
if not email:
raise exceptions.AuthenticationFailed('Users must have an username')
username = email.split("#")[0]
user = self.model(username=username)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, username=None):
user = self.create_user(email=email, password=password)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractUser):
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
is_test = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = AuthManager()
userTest(myApp) > views.py
from rest_framework import viewsets
from apps.userTest.models import User
from apps.userTest.serializers import UserSerializer
class UserViewSet(viewsets.ReadOnlyModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer