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.
Related
models
from django.contrib.auth.models import User
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, UserManager, PermissionsMixin
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=255, unique=True)
objects = UserManager()
USERNAME_FIELD = 'username'
error:
(env) ➜ authorization python manage.py createsuperuser
Username: soubhagya
Password:
Password (again):
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute
output = self.handle(*args, **options)
File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/contrib/auth/models.py", line 163, in create_superuser
return self._create_user(username, email, password, **extra_fields)
File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/contrib/auth/models.py", line 144, in _create_user
user = self.model(username=username, email=email, **extra_fields)
File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/db/models/base.py", line 503, in __init__
raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
TypeError: User() got an unexpected keyword argument 'email'
(env) ➜ autherization
I am trying to create a superuser inside Django shell
Getting above error.
Please take a look what can be the reason
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
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!
I found a lot of content on the AppRegistryNotReady Exception, but none of them seem defenitive. I just wanted my 2 cents of info on the topic.
My django project was working fine. I created a new app, and created the following model. No view, no urls nothing. Just a model.
from __future__ import unicode_literals
from django.db import models
# Create your models here.
from django.conf import settings
from django.core.exceptions import ValidationError
from django.contrib.auth import get_user_model
User = get_user_model()
class File(models.Model):
path = models.TextField() #The path does not include MEDIA_ROOT, obviously
filename = models.CharField(max_length=500)
# file = models.FileField(upload_to=upload_to)
file = models.FileField(upload_to=path+filename)
user = models.ForeignKey(settings.AUTH_USER_MODEL, models.PROTECT) #Protects User from being deleted when there are files left
def clean(self):
#Check if path has a trailing '/'
if self.path[-1]!='/':
self.path = self.path+"/"
if self.filename[0]=='/':
self.filename = self.filename[1:]
#Get the full path
username = self.user.__dict__[User.USERNAME_FIELD] #Need to do this the roundabout way to make sure that this works with CUSTOM USER MODELS. Else, we could have simply went for self.user.username
self.path = "tau/"+username+"/"+self.path
def save(self, *args, **kwargs):
self.full_clean()
return super(File, self).save(*args, **kwargs)
def __str__(self):
if path[-1]=='/':
text = "\n"+str(path)+str(filename)
else:
text = "\n"+str(path)+"/"+str(filename)
return text
Then I tried to makemigrations on the model. And ended up with the following error.
(test) ~/Workspace/WebDevelopment/Django/test/stud$python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute
django.setup()
File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/raghuram/Workspace/WebDevelopment/Django/test/stud/tau/models.py", line 10, in <module>
User = get_user_model()
File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 163, in get_user_model
return django_apps.get_model(settings.AUTH_USER_MODEL)
File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/lib/python2.7/site-packages/django/apps/registry.py", line 192, in get_model
self.check_models_ready()
File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/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.
Just for the sake of completing the test, I changed my model to this,
class File(models.Model):
file = models.FileField()
And that stopped the exception. So my guess is that the Exception was being raised by this.
from django.contrib.auth import get_user_model
User = get_user_model()
But I need to use that, since Im working with custom User Model. Any idea on how I can make it happen?
AbstractBaseUser provides a get_username() method which you can use instead. It practically does the same as what you're doing: return getattr(self, self.USERNAME_FIELD).
class File(models.Model):
...
def clean(self):
#Check if path has a trailing '/'
if self.path[-1]!='/':
self.path = self.path+"/"
if self.filename[0]=='/':
self.filename = self.filename[1:]
#Get the full path
username = self.user.get_username()
self.path = "tau/"+username+"/"+self.path
The reason your original method failed is because get_user_model() is executed when the module is first imported, at which time the app registry is not fully initialized. If you need to use get_user_model() in a models.py file, you should call it within a function or method, not at the module level:
class File(models.Model):
...
def clean(self):
User = get_user_model()
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')