Creating Django users with just an email and password - UserCreationForm - python

I have the need of create an user account in my application using just the email and password fields. Due to this, my custom user model in my models.py is:
I customize the UserManager to create user
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def _create_user(self, email, password, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError("Users must have an email address")
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):
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)
And my User model is:
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import ugettext_lazy as _
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True, null=True,
help_text=_('Required. Letters, digits and ''#/./+/-/_ only.'),
validators=[RegexValidator(r'^[\w.#+-]+$', _('Enter a valid email address.'), 'invalid')
])
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_('Designates whether the user can log into this site.'),
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
objects = UserManager()
USERNAME_FIELD = "email"
class Meta:
db_table = 'auth_user'
verbose_name_plural = 'Usuarios en la plataforma'
def __str__(self):
return "#{}".format(self.email)
In my settings I've add:
AUTH_USER_MODEL = ‘my_app_name.User’
CREATE USERS - UserCreationForm pre-built class
To create an user, I am using of the UserCreationForm class pre-built in the django core.
In this class the username field is used such as denoted here
According to the above, in my forms.py I have:
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
class CustomUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = get_user_model()
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = get_user_model()
class UserCreateForm(UserCreationForm):
class Meta:
fields = ("email", "password1", "password2",)
model = get_user_model()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["email"].label = "Email address"
When I try execute the python manage.py makemigrations , I get this traceback output error
bgarcial#elpug ‹ testing ●● › : ~/workspace/ihost_project
[1] % python manage.py makemigrations accounts
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute
django.setup()
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/apps/registry.py", line 115, in populate
app_config.ready()
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/bgarcial/workspace/ihost_project/accounts/admin.py", line 8, in <module>
from .forms import CustomUserChangeForm, CustomUserCreationForm
File "/home/bgarcial/workspace/ihost_project/accounts/forms.py", line 16, in <module>
class CustomUserCreationForm(UserCreationForm):
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/forms/models.py", line 257, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (username) specified for User
(ihost)
bgarcial#elpug ‹ testing ●● › : ~/workspace/ihost_project
Of course, I am using UserCreationForm django class core, I am forcing to use the django core functionalities in which the username field is required
How to can I remove the username or modify this?
I know the modify the django core is not recommended, but, how to can I create an user without include the username field making use of UserCreationForm django class core?
I try override the save method of my form in where I create the users, but I don't have clear the process, I think that the core of my inconvenient is in the use of UserCreationForm django class core ..
class UserCreateForm(UserCreationForm):
class Meta:
fields = ("email", "password1", "password2",)
model = get_user_model()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["email"].label = "Email address"
def save(self, commit=True):
user = super(UserCreateForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
# Tell to Django that not check the username
if commit:
user.save()
return user
If somebody can point me in the right direction will be very much appreciated. :)

I've found a solution that works.
anyways, feel free to suggest better solutions!
Like my inconvenient/error was related with the use of the UserCreationForm class pre-built in the django core which use the username field in their logic, then I proceeded to make the following:
In my forms.py in my class CustomUserCreationForm is a child of the class UserCreationForm, I've override/add to Meta class the attribute fields, using the email field instead of username field.
This question post help me with it.
My class CustomUserCreationForm stay as follow:
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = get_user_model()
fields = ('email',)
Then, I proceeded to perform my migrations:
[1] % python manage.py makemigrations accounts
SystemCheckError: System check identified some issues:
ERRORS:
<class 'accounts.admin.UserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.User'.
This error showed me that the username field is not an attribute of my User model.
This means that Django follows trying to ask the username field, even though I overwritten the fields value with the email field.
Of course this is logic because I am still inherit from UserCreationForm class pre-built in the django core
Then, I've add the username field to my User model with null=True attribute, and of this way, the username does not required in the user account creation:
class User(AbstractBaseUser, PermissionsMixin):
# I had add the username field despite that I don't use in my User model
username = models.CharField(_('username'), max_length=30, null=True,
help_text=_('Required. 30 characters or fewer. Letters, digits and ''#/./+/-/_ only.'),
validators=[RegexValidator(r'^[\w.#+-]+$', _('Enter a valid username.'), 'invalid')
])
email = models.EmailField(unique=True, null=True,
help_text=_('Required. Letters, digits and ''#/./+/-/_ only.'),
validators=[RegexValidator(r'^[\w.#+-]+$', _('Enter a valid email address.'), 'invalid')
])
...
Of this way, I execute my migrations
bgarcial#elpug ‹ testing ●● › : ~/workspace/ihost_project
[1] % python manage.py makemigrations accounts
Migrations for 'accounts':
accounts/migrations/0001_initial.py:
- Create model User
(ihost)
bgarcial#elpug ‹ testing ●● › : ~/workspace/ihost_project
python manage.py migrate accounts ...
And my username field still persist in my custom user schema, just that is not required and when I created an user from my UserCreateForm class which inherit from UserCreationForm, I can create an user account with just email and password
I don`t know if this is the best approach to address this inconvenient.
Feel free to suggest improvements!

Related

TypeError: User() got unexpected keyword arguments: 'password2' : Django JWT Authentication

I am trying to build a user authentication app using django JWT token, when i try to test my user authentication api and validate the password and password2 , it generate the following error:
TypeError: User() got unexpected keyword arguments: 'password2'
My serializers.py is as follows:
from rest_framework import serializers
from account.models import User
class UserRegistrationSerializers(serializers.ModelSerializer):
password2=serializers.CharField(style={'input_type':'password'}, write_only=True)
class Meta:
model = User
fields=['email','name','tc','password','password2']
extra_kwargs={
'password':{'write_only':True}
}
def validate(self, attrs):
password=attrs.get('password')
password2=attrs.get('password2')
if password != password2:
raise serializer.ValidationError("Password and Confirm Password Does not match")
return attrs
def validate_data(self, validate_data):
return User.objects.create_user(**validate_data)
and my views.py is as follows:
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from account.serializers import UserRegistrationSerializers
# Create your views here.
class UserRegistrationView(APIView):
def post(self, request, format=None):
serializer= UserRegistrationSerializers(data=request.data)
if serializer.is_valid(raise_exception=True):
user= serializer.save()
return Response({'msg':'Registration Successful'}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
my models.py file is as follows:
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, email, name, tc, password=None, password2=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
name=name,
tc=tc,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, name, tc, password=None):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
email,
password=password,
name=name,
tc=tc,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='Email',
max_length=255,
unique=True,
)
#date_of_birth = models.DateField()
name= models.CharField(max_length=200)
tc=models.BooleanField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name','tc']
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return self.is_admin
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
The full traceback is as follows:
Traceback (most recent call last): File
"D:\jwt\lib\site-packages\django\core\handlers\exception.py", line 55,
in inner
response = get_response(request) File "D:\jwt\lib\site-packages\django\core\handlers\base.py", line 197, in
_get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\jwt\lib\site-packages\django\views\decorators\csrf.py", line 54,
in wrapped_view
return view_func(*args, **kwargs) File "D:\jwt\lib\site-packages\django\views\generic\base.py", line 103, in
view
return self.dispatch(request, *args, **kwargs) File "D:\jwt\lib\site-packages\rest_framework\views.py", line 509, in
dispatch
response = self.handle_exception(exc) File "D:\jwt\lib\site-packages\rest_framework\views.py", line 469, in
handle_exception
self.raise_uncaught_exception(exc) File "D:\jwt\lib\site-packages\rest_framework\views.py", line 480, in
raise_uncaught_exception
raise exc File "D:\jwt\lib\site-packages\rest_framework\views.py", line 506, in
dispatch
response = handler(request, *args, **kwargs) File "D:\djangoauthapi1\account\views.py", line 13, in post
user= serializer.save() File "D:\jwt\lib\site-packages\rest_framework\serializers.py", line 212, in
save
self.instance = self.create(validated_data) File "D:\jwt\lib\site-packages\rest_framework\serializers.py", line 981, in
create
raise TypeError(msg) TypeError: Got a TypeError when calling User.objects.create(). This may be because you have a writable field
on the serializer class that is not a valid argument to
User.objects.create(). You may need to make the field read-only, or
override the UserRegistrationSerializers.create() method to handle
this correctly. Original exception was: Traceback (most recent call
last): File
"D:\jwt\lib\site-packages\rest_framework\serializers.py", line 962, in
create
instance = ModelClass._default_manager.create(**validated_data) File "D:\jwt\lib\site-packages\django\db\models\manager.py", line 85,
in manager_method return getattr(self.get_queryset(), name)(*args,
**kwargs) File "D:\jwt\lib\site-packages\django\db\models\query.py", line 669, in create
obj = self.model(**kwargs) File "D:\jwt\lib\site-packages\django\db\models\base.py", line 565, in
init
raise TypeError( TypeError: User() got unexpected keyword arguments: 'password2'
i have figured out each line of code but i am unable to catch what is exactly the error, please needful help is required.
Because your serializer has password2 but User model does not have.
Just pop password2 into validated_data
from rest_framework import serializers
from account.models import User
class UserRegistrationSerializers(serializers.ModelSerializer):
password2=serializers.CharField(style={'input_type':'password'}, write_only=True)
class Meta:
model = User
fields=['email','name','tc','password','password2']
extra_kwargs={
'password':{'write_only':True}
}
def validate(self, attrs):
password=attrs.get('password')
password2=attrs.pop('password2')
if password != password2:
raise serializer.ValidationError("Password and Confirm Password Does not match")
return attrs
def create(self, validate_data):
return User.objects.create_user(**validate_data)

Django request.user not working when using auth_user_model in models.py

I am using the User model (which is a custom one) in my models.py by import settings and getting it through the AUTH_USER_MODEL but it seems like in my views that the request.user is not recognize as an instance of the user class.
Here is the model
from django.db import models
from django.conf import settings
from django.utils import timezone
User = settings.AUTH_USER_MODEL
class Site(models.Model):
name = models.CharField(
max_length=100,
)
slug = models.SlugField(max_length=20)
admin = models.ForeignKey(
User,
related_name="administrators",
on_delete=models.SET_NULL,
blank=True,
null=True,
)
people = models.ManyToManyField(User)
def __str__(self):
return self.name
HERE is the logic in the views
def create_site(request):
user = request.user
print(user)
form = CreateSiteForm(
request.POST or None,
initial={
"admin": user,
},
)
if form.is_valid():
form.save()
return redirect("projects")
context = {
"form": form,
}
return render(request, "tracking/create-site.html", context)
Here is the error from the terminal
return self.is_bound and not self.errors
File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\forms\forms.py", line 170, in errors
self.full_clean()
File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\forms\forms.py", line 374, in full_clean
self._post_clean()
File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\forms\models.py", line 408, in _post_clean
self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\forms\models.py", line 63, in construct_instance
f.save_form_data(instance, cleaned_data[f.name])
File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\db\models\fields\__init__.py", line 910, in save_form_data
setattr(instance, self.name, data)
File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\db\models\fields\related_descriptors.py", line 215, in __set__
raise ValueError(
ValueError: Cannot assign "'papis'": "Site.admin" must be a "User" instance.
The request.user returns the username of the user. I am wondering what is the problem.
Any help would be appreciated.
Thanks in advance......
use this instead of the User in the models
from django.contrib.auth.models import User
and change your views to this
user=request.user.id

How to change manager for custom User model

I've defined a custom user model:
class User(AbstractUser):
REQUIRED_FIELDS = []
USERNAME_FIELD = 'email'
email = models.EmailField(
_('email address'),
max_length=150,
unique=True,
help_text=_('Required. 150 characters or fewer. Must be a valid email address.'),
error_messages={
'unique':_("A user with that email address already exists."),
},
)
The point of it being to use an email address instead of username.
I've put this in settings:
# custom user model
AUTH_USER_MODEL = 'workoutcal.User'
The user model works, but there's one problem. I can't create superusers:
(workout) n155-p250:workout sahandzarrinkoub$ ./manage.py createsuperuser
Email address: sahandz#kth.se
Password:
Password (again):
Traceback (most recent call last):
File "./manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 59, in execute
return super().execute(*args, **options)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
output = self.handle(*args, **options)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 179, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
TypeError: create_superuser() missing 1 required positional argument: 'username'
Seems like the create_superuser method used has username as a required argument. I've read in the docs that I need to implement my own CustomUserManager. I've already done so here:
class CustomUserManager(BaseUserManager):
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
now = timezone.now()
if not email:
raise ValueError('email must be set')
email = self.normalize_email(email)
user = User(email = email, is_staff=is_staff,
is_superuser=is_superuser, date_joined=now,
**extra_fields)
user.set_password(password)
user.save()
return user
def create_user(self, email, password, **extra_fields):
return self._create_user(email, password, False, False, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
return self._create_user(email, password, True, True, **extra_fields)
It seems clear that my CustomUserManager isn't managing the User model. There seems to be no documentation telling me where to actually set the CustomUserManager as the actual manager for the User model. Could somebody tell me how to do that?
You also need to tell the new user to use the new manager:
class User(AbstractUser): # in your custom user
#...
objects = CustomUserManager()
#...
Django does the same thing in the source code at line 325
As for:
There seems to be no documentation telling me where to actually set the CustomUserManager as the actual manager for the User model.
Yes, there is actually a nice doc for that too, but explained in a more general way:
https://docs.djangoproject.com/en/2.0/topics/db/managers/

Why are "Models aren't loaded yet"?

I am trying to install django-registration-redux with a customUser.
I have included this in my settings.py:
AUTH_USER_MODEL = 'app.customUser'
Registration Form is in a directory ../registration/forms.py:
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.forms import UserCreationForm
from .users import UserModel, UsernameField
User = UserModel()
class RegistrationForm(UserCreationForm):
required_css_class = 'required'
email = forms.EmailField(label=_("E-mail"))
class Meta:
model = customUser
fields = ('email')
Additionally, models.py has the following:
from __future__ import unicode_literals
from django.db import models
# Create your models here.
import datetime
import hashlib
import random
import re
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.db import models
from django.template import RequestContext, TemplateDoesNotExist
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from django.utils.timezone import now as datetime_now
from django.utils import six
from .users import UserModel, UserModelString
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
from django.contrib.auth.admin import UserAdmin
class customUserManager(BaseUserManager):
def create_user(self, email, password=None):
"""
Creates and saves a User with the given email, date of
birth 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, date of
birth and password.
"""
user = self.create_user(email,
password=password,
)
user.is_active = True
user.is_admin = True
user.save(using=self._db)
return user
class customUser(AbstractBaseUser):
email = models.EmailField(verbose_name='email address', max_length=255, unique=True)
first_name = models.CharField(max_length=50, null=True)
middle_name = models.CharField(max_length=50, null=True)
last_name = models.CharField(max_length=50, null=True)
is_active = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
objects = customUserManager()
USERNAME_FIELD = 'email'
class customUserAdmin(UserAdmin):
# The forms to add and change user instances
#form = UserChangeForm
#add_form = RegisterationForm
class RegistrationManager(models.Manager):
"""
"""
Here is the Traceback:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
django.setup()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/Desktop/app/sites/models.py", line 21, in <module>
from .users import UserModel, UserModelString
File "/Users/Desktop/app/sites/users.py", line 4, in <module>
UserModel = get_user_model()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 150, in get_user_model
return django_apps.get_model(settings.AUTH_USER_MODEL)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/registry.py", line 199, in get_model
self.check_models_ready()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/registry.py", line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
If I remove the () in get_user_model in my users.py, I get this error:
users.py
from django.conf import settings
from django.contrib.auth import get_user_model
UserModel = get_user_model
def UserModelString():
try:
return settings.AUTH_USER_MODEL
except AttributeError:
return 'auth.User'
def UsernameField():
return getattr(UserModel(), 'USERNAME_FIELD', 'email')
Error:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 155, in get_user_model
"AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'app.customUser' that has not been installed
Here is the documentation of get_user_model function that might help.
Generally speaking, you should reference the User model with the
AUTH_USER_MODEL setting in code that is executed at import time.
get_user_model() only works once Django has imported all models.
The problem is in file ../registration/forms.py:
User = UserModel()
UserModel is executing in import time, which is wrong and throws the exception 'Models aren't loaded yet'. Use UserModel() directly inside your form methods/functions where it needed. Look at a few examples here.
Hope this helps.

Custom django user registration form

I am learning Django and I am trying to make my own custom registration forms. I currently ran into this error:
Unknown field(s) (user) specified for User
Here is the traceback:
Traceback:
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/core/handlers/base.py" in get_response
101. resolver_match = resolver.resolve(request.path_info)
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/core/urlresolvers.py" in resolve
320. sub_match = pattern.resolve(new_path)
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/core/urlresolvers.py" in resolve
222. return ResolverMatch(self.callback, args, kwargs, self.name)
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/core/urlresolvers.py" in callback
229. self._callback = get_callable(self._callback_str)
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/utils/functional.py" in wrapper
32. result = func(*args)
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/core/urlresolvers.py" in get_callable
96. mod = import_module(mod_name)
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/utils/importlib.py" in import_module
40. __import__(name)
File "/Users/username/Development/django_tutorial/bin/django_test/django_test/views.py" in <module>
10. from forms import MyRegistrationForm
File "/Users/username/Development/django_tutorial/bin/django_test/django_test/forms.py" in <module>
7. class MyRegistrationForm(UserCreationForm):
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/forms/models.py" in __new__
292. raise FieldError(message)
Exception Type: FieldError at /accounts/register/
Exception Value: Unknown field(s) (user) specified for User
I think the problem resides within this piece of code:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class MyRegistrationForm(UserCreationForm):
email = forms.EmailField(required = True)
# hold anything that isnt a form field (meta data)
class Meta:
model = User
fields = ('user', 'email', 'password1', 'password2')
def save(self, commit = True):
# save(commit = T/F) means save or dont save yet
# calls the super method of this class (UserCreationForm) and calling it's save method with input as false
user = super(MyRegistrationForm, self).save(commit = False)
# cleaned_data makes things save to put in data base
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
I think you mean field "username". Model User haven't field "user".
Right:
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')

Categories

Resources