OAuth2 custom basic user model - django

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

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.

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

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()

Field error , trying to reference custom user model

Got no idea what's going on here. First time using a custom user model so I'm having trouble referencing the user object in views. I know I need to use 'get_user_model' , but I'm not sure how to implement it. I tried doing a couple things but I'm still stuck.
error
FieldError at /mingle/
Cannot resolve keyword 'user' into field. Choices are: date_joined, description, email, given_vote, id, is_active, is_admin, is_staff, is_superuser, last_login, logentry, matches, password, photo, username, uservote
Request Method: GET
Request URL: http://localhost:8000/mingle/
Django Version: 2.2.3
Exception Type: FieldError
Exception Value:
Cannot resolve keyword 'user' into field. Choices are: date_joined, description, email, given_vote, id, is_active, is_admin, is_staff, is_superuser, last_login, logentry, matches, password, photo, username, uservote
Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py in names_to_path, line 1420
Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3
Python Version: 3.7.3
Python Path:
['/Users/papichulo/Documents/DatingApp',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
'/Users/papichulo/Library/Python/3.7/lib/python/site-packages',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages']
Server time: Fri, 3 Apr 2020 23:46:27 +0000
Error at description = Profile.objects.get(user=request.user).description
**views.py, part that's giving me an error **
from __future__ import unicode_literals
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.contrib.auth import login, logout, authenticate
from dating_app.forms import RegistrationForm,ProfileUpdateForm
from .models import Profile
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
import os
from django.core import serializers
import json
from django.contrib.auth import get_user_model
User = get_user_model()
def mingle(request):
try:
user = (Profile.objects.exclude(id=request.user.id).exclude(uservote__voter=request.user).order_by('?')[0])
except IndexError:
user = None
print(User.username)
try:
description = models.Profile.objects.get(user=request.user).description
except models.Profile.DoesNotExist:
create = Profile.objects.get_or_create(user = request.user)
return redirect('profile')
match = models.Profile.objects.get(user=request.user).matches.all()
context = dict(user = user, match = match)
return render(request, 'dating_app/mingle.html', context)
models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser,BaseUserManager, User
from dating_project import settings
class ProfileManager(BaseUserManager):
def create_user(self, username, email,description,photo, password=None):
if not email:
raise ValueError("You must creat an email")
if not username:
raise ValueError("You must create a username!")
if not description:
raise ValueError("You must write a description")
if not photo:
raise ValueError("You must upload a photo")
user = self.model(
email=self.normalize_email(email),
username = username,
description= description,
photo= photo,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email,description,photo, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
description=description,
photo=photo,
)
user.is_admin=True
user.is_staff=True
user.is_superuser=True
user.save(using=self._db)
return user
class Profile(AbstractBaseUser):
email = models.EmailField(verbose_name="email")
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
#what I added
description = models.TextField()
photo = models.ImageField(upload_to='profile_photo',blank=False, height_field=None, width_field=None, max_length=100)
matches = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='+', blank=True)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['description','photo','email']
objects = ProfileManager()
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self,app_label):
return True
class UserVote(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
voter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='given_vote', on_delete=models.CASCADE)
vote = models.BooleanField(default=False)
class Meta:
unique_together = (('user', 'voter'))

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" ?