I can't seem to figure out why my unit test is failing for the following
Traceback (most recent call last):
File "/app/core/tests/test_admin.py", line 26, in test_users_listed
self.assertContains(res, self.user.name)
AttributeError: 'AdminSiteTests' object has no attribute 'user'
test_admin.py
from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
class AdminSiteTests(TestCase):
def setup(self):
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(
email='admin#test.com',
password='test123'
)
self.client.force_login(self.admin_user)
self.user = get_user_model().objects.create_user(
email='test#test.com',
password='test123',
name='test name'
)
def test_users_listed(self):
"""Test that users are listed on user page"""
url = reverse('admin:core_user_changelist')
res = self.client.get(url)
self.assertContains(res, self.user.name)
self.assertContains(res, self.user.email)
admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from core import models
class UserAdmin(BaseUserAdmin):
ordering = ['id']
list_display = ['email', 'name']
admin.site.register(models.User, UserAdmin)
models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
"""Creates and saves a new user"""
if not email:
raise ValueError('Users must have a email address')
user = self.model(email=self.normalize_email(email), **extra_fields)
# Must encrypt password using set_password() that comes with BaseUserManager
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""Creates and saves new superuser"""
user = self.create_user(email, password)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
"""Custom user model that supports using email instead of username"""
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
I am creating the user in the setup function for the rest of my tests but I'm thinking maybe the setup function isn't getting called to create the user?
All other tests are passing. Including a test that checks whether a user has been created. Any help would be apperciated
Related
Here is my model in the user app
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class UserTable(AbstractBaseUser, PermissionsMixin):
USERNAME_FIELD='email'
objects = UserManager()
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
phone = models.CharField(max_length=255, default=None)
is_active = models.BooleanField(default=False)
Here is my admin.py inside the user app.
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import UserTable
admin.site.register(UserTable, UserAdmin)
I also included in my settings.py
INSTALLED_APPS = [
....
'user.apps.UserConfig',
....
]
This is the error when I run python manage.py migrate
(admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'user.UserTable'.
The value of 'list_display[0]' refers to 'username', which is not a callable, an attribute of 'UserAdmin', or an attribute or method on 'user.UserTable'.
I dont know why, I thought when I set objects = UserManager() fields like username, first_name, last_name is setted up. I also user USERNAME_FIELD to set email replacing the username primary key.
You are supposed to write ur own UserManager
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
class UserManager(BaseUserManager):
def create_user(self, email, password, **extra_fields):
if not email:
raise ValueError('User must have an email address')
user = self.model(
email=self.normalize_email(email),
**extra_fields
)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
user = self.create_user(
email,
password,
**extra_fields
)
return user
Just a small comment in UserTable model, make
is_active = models.BooleanField(default=True) To be able to login
And in settings.py file add
AUTH_USER_MODEL = 'user.UserTable'
Edit
I noticed that you are calling AbstractBaseUser, BaseUserManager in a wrong way
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
Try it out and told me if there is any problem!
The problem is because you are inheriting from AbstractBaseUser (which does not come with a username field):
class AbstractBaseUser(models.Model):
password = models.CharField(_('password'), max_length=128)
last_login = models.DateTimeField(_('last login'), blank=True, null=True)
... # No definition for usename in this class
and then using UserAdmin (which requires username as field) as your admin:
#admin.register(User)
class UserAdmin(admin.ModelAdmin):
...
# The admin needs the username field as described by ordering
# But your custom user model doesn't have it
ordering = ('username',)
There are a number of ways to fix this, but one way is to define your own model admin for your custom user:
from django.contrib import admin
class MyAdmin(admin.ModelAdmin):
pass
admin.site.register(UserTable, MyAdmin)
I'm trying to test the creation of an user in Django. But my user model is not the standard one (email is the username).
models.py
from django.contrib.auth.models import AbstractUser, UserManager as AbstractUserManager
class UserManager(AbstractUserManager):
def create_user(self, email, password=None, is_active=True, is_staff=False, is_admin=False):
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
class CustomUser(AbstractUser):
objects = UserManager()
username = None
first_name = models.CharField(max_length=150)
last_name = models.CharField(max_length=150)
email = models.EmailField(unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
tests.py
from django.contrib.auth import get_user_model
class CustomUserTests(TestCase):
def test_create_user(self):
user = get_user_model()
utilisateur = user.create_user(
email='test#tester.com',
password='testpass123',
)
self.assertEqual(utilisateur.email, 'test#tester.com')
Error
line 10, in test_create_user
utilisateur = user.create_user( AttributeError: type object 'CustomUser' has no attribute 'create_user'
Something is missing but I don't know how to test well this...
Thanks a lot
CustomUser' has no attribute 'create_user'
create_user is not present on the CustomUser model and that's what the error is saying. The method is present on the UserManager and the manager is defined on the user model as objects = UserManager().
So to access the method, you need to use user.objects.create_user.
I have created a model class which extends from AbstractUser to handle token authentication, how do I get date_joined property of the modal's object when querying it in django rest framework views.py?
Models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from .managers import CustomUserManager
# Create your models here.
class CustomUser(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
date_of_birth = models.DateField(blank=True, null=True)
def __str__(self):
return self.email
class Task(models.Model):
title = models.CharField(max_length=200)
completed = models.BooleanField(default=False, blank=True, null=True)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
def __str__(self):
return self.title
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
Here is my 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)
This my drf view:
#api_view(['GET'])
#permission_classes([IsAuthenticated])
def report2(request):
user_data = CustomUser.objects.get(id=request.user.id)
print("User data ",user_data)
return Response("date_joined", status=status.HTTP_200_OK)
The user_data only returns email_id, I expect it to return all the attributes of the table including date_joined.
Below is an image from my database:
Kindly someone guide me, how can I get date_joined attribute of the CustomUser object in my view function?
Thanks
i have this error -->
raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs))
TypeError: 'class Meta' got invalid attribute(s): models
i want create page where people can register but i have this error. how fix?
i search google but couldn't find a reason. what's the problem?
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.contrib.auth import password_validation
from django.db import models
class SignUp(models.Model):
class Meta:
models=User
models.py
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db import models
from django.utils.translation import ugettext_lazy as _
class UserManager(BaseUserManager):
"""Define a model manager for User model with no username field."""
use_in_migrations = True
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 given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
"""Create and save a regular User with the given email and password."""
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
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)
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)
class User(AbstractUser):
"""User model."""
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
views.py
from . import forms
from django.shortcuts import render
from django.http import HttpResponse
import datetime
from django.contrib.auth import authenticate
def regform(request):
if request.method == 'POST':
form = SignUp(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
user = authenticate(email=email, password=raw_password)
login(request, user)
return redirect('home')
else:
form = SignUp()
return render(request, 'home/home.html', {'form': form})
You are here defining a Model, but you likely want to define a ModelForm. Note that the Meta of a ModelForm uses model, not models:
from django import forms
from django.contrib.auth.models import User
class SignUp(forms.ModelForm):
class Meta:
model = User
fields = '__all__'
In the case of creating a User object, you better inherit from UserCreationForm, since this will store the hashed password in the database:
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUp(UserCreationForm):
class Meta:
model = User
fields = '__all__'
By using a generic ModelForm, it will store the raw password in the form, and then authentication will fail (because this checks the hashed password).
It should be ModelForm instead of models.Model
from django.contrib.auth.models import User
from django.forms import ModelForm
class SignUp(ModelForm):
class Meta:
model=User
fields = [add your fields here]
comment out
'rest_framework.authtoken',
then you will able to makemigrations and migrate also
I've created a CustomUser from AbstractUser in Django 1.9. Add on admin.sites.register when I was create superuser, django have created successful but when I was log in on system the user didn't exists.
Follow the code:
On customuser/models.py:
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class CustomUserManager(BaseUserManager):
def create_user(self, username, email, first_name, last_name, cpf, password=None):
user = self.model(
username=username,
email=email,
first_name=first_name,
last_name=last_name,
cpf=cpf
)
return user
def create_superuser(self, username, email, first_name, last_name, cpf, password):
user = self.create_user(username, email, first_name, last_name, cpf,
password=password)
user.is_super_user = True
user.save()
return user
class CustomUser(AbstractUser):
SEXO_CHOICES = (
(u'Masculino', u'Masculino'),
(u'Feminino', u'Feminino'),
)
cpf = models.BigIntegerField(unique=True)
phone = models.CharField(max_length=15, blank=True)
is_super_user = models.BooleanField(default=False)
data_de_nascimento = models.DateField(null=True)
sexo = models.CharField(max_length=9, null=True, choices=SEXO_CHOICES)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', 'first_name', 'last_name', 'cpf']
objects = CustomUserManager()
On settins.py, I add the line:
INSTALLED_APPS = [
...
'customuser',
]
...
AUTH_USER_MODEL = 'customuser.CustomUser'
And my customuser/admin.py:
from django.contrib import admin
from models import CustomUser, CustomUserManager
admin.site.register(CustomUser)
Thanks a lot for your help.
See these docs on making custom user work with admin site.
UPDATE:
Sorry, previously I thought, you were inheriting your model from AbstractBaseUser, therefore that answer was giving you error.
Since, you're inheriting from AbstractUser, your subclass will automatically get is_staff field. So, you'll just need to set is_staff to True in create_superuser method.
class CustomUserManager(...):
# ...
def create_superuser(...):
# ...
user.is_staff = True
user.save()
return user