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'))
Related
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
I complete makemigrations and migrate then create a superuser. After this
http://127.0.0.1:8000/admin i try to log in then show this error
Please enter the correct Email and password for a staff account. Note that both fields may be case-sensitive
seetings.py
AUTH_USER_MODEL = 'user.CustomUser'
**models.py**
from django.db import models
from django.contrib.auth.models import AbstractUser,BaseUserManager
class CustomUserManager(BaseUserManager):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
def create_user(self, email, password=None):
if not email:
raise ValueError('User must have an email id')
user=self.model(
email=self.normalize_email(email)
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password=None):
user=self.create_user(
email,
password=password
)
user.is_admin = True
user.save(using=self._db)
return user
class CustomUser(AbstractUser):
#only add email field for login
email = models.EmailField(
verbose_name='Email',
max_length=50,
unique=True
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = CustomUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def __str__(self):
return self.email
***admin.py***
from django.contrib import admin
from django.contrib.auth import get_user_model
user=get_user_model()
admin.site.register(user)
i had this problem.
you should define is_staff=True in create_superuser function and you should pass **kwargs as argument in this function.
i hope your problem solve.
I'm adding Django Model to a graphql api using the AbstractBaseUser custom user model. The Admin works fine except that I get an error when trying to access the graphql api, 'You need to pass a valid Django Model in UserProfile.Meta, received "None"'
I've tried adding AUTH_USER_MODEL = 'noxer_app.MyUser' to settings, yet it doesn't work
In models.py:
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class MyUserManager(BaseUserManager):
def create_user(self, email, first_name, last_name, company, company_reg_no, address, phone, image, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
first_name=first_name,
last_name=last_name,
company=company,
company_reg_no=company_reg_no,
address=address,
phone=phone,
image=image,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, first_name, last_name, company, company_reg_no, address, phone, image, password):
user = self.create_user(
email,
password=password,
first_name=first_name,
last_name=last_name,
company=company,
company_reg_no=company_reg_no,
address=address,
phone=phone,
image=image,
)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(max_length=255, default='')
last_name = models.CharField(max_length=255, default='')
company = models.CharField(max_length=255, default='')
company_reg_no = models.CharField(max_length=255, default='')
address = models.CharField(max_length=400, default='')
phone = models.CharField(max_length=13, default='')
image = models.ImageField(default='noimage.jpg', upload_to = 'profile_pics')
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name', 'company', 'company_reg_no', 'address', 'phone', 'image']
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 True
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
app.schema.py
import graphene
from graphene import relay, ObjectType
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from django.contrib.auth.models import AbstractUser
from django.contrib.auth import get_user_model
from noxer_app.models import MyUser
class UserProfile(DjangoObjectType):
class meta:
model = MyUser
class Query(graphene.ObjectType):
all_users = graphene.List(UserProfile)
def resolve_all_users(self, info, **kwargs):
return MyUser.objects.all()
I expect to see the Graphql api interface, but I get this error:
You need to pass a valid Django Model in UserProfile.Meta, received "None".
I think it should be class Meta not class meta. The Meta starts with a capital. That's why it doesn't recognize that you describe the model.
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" ?
I am new to Django, trying to create a custom user for my project. When I am running the server, it raises No module named 'django.contrib.customuser' and sometimes, Manager isn't available; auth.User has been swapped for Mysite.CustomUser. Even i changed my settings: django.contrib.auth to django.contrib.custommuser. Please someone help me solving this. Here's my code
models.py:
from datetime import datetime
from django.db import models
from django.contrib.auth.models import User, BaseUserManager, AbstractUser, AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
class CustomUserManager(BaseUserManager):
def _create_user(self, username, email, u, password, is_staff, is_active, **extra_fields):
now = datetime.now()
if not email:
raise ValueError('Users must have an email address')
email = self.normalize_email(email)
user = self.model(username=username, email=email, u=u, password=password,
is_staff=is_staff, is_active=False, last_login=now, date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, email, u, password = None, **extra_fields):
return self._create_user(username, email, u, False, False, **extra_fields)
def create_superuser(self, username, email, u, password = None):
user = self._create_user(username, email, u, password, True, True)
user.set_password(password)
user.is_active=True
user.is_admin = True
user.is_superuser = True
user.save(using=self._db)
return user
class CustomUser(AbstractBaseUser):
username = models.CharField(max_length=30)
email = models.EmailField(max_length=30, unique=True, db_index=True)
password1 = models.CharField(max_length=30)
password2 = models.CharField(max_length=30)
CHOICES= (('LinkedinUser', 'LinkedinUser'),('FacebookUser', 'FacebookUser'),)
u = models.CharField(choices=CHOICES, max_length=20, default=0)
date_joined = models.DateTimeField(_('date joined'), default=datetime.now)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
REQUIRED_FIELDS = ('username', 'u')
USERNAME_FIELD = 'email'
objects = CustomUserManager()
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __str__(self): # __unicode__ on Python 2
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
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):
return self.is_admin
forms.py
from django import forms
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from .models import CustomUser#, LinkedInUser, FacebookUser
import re
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
class CustomUserForm(forms.ModelForm):
username = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("username"), error_messages={ 'invalid': _("This value must contain only letters, numbers and underscores.") })
email = forms.EmailField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Email address"))
password1 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password"))
password2 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password (again)"))
CHOICES= (('LinkedinUser', 'LinkedinUser'),('FacebookUser', 'FacebookUser'),)
u = forms.ChoiceField(choices=CHOICES, label='ID', widget=forms.RadioSelect())
class Meta :
model = CustomUser
fields = [ 'username', 'email', 'password1', 'password2', 'u' ]
User = get_user_model()
def clean_name(self):
try:
user = User.objects.get(username__iexact=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(_("The username already exists. Please try another one."))
def clean(self):
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_("The two password fields did not match."))
return self.cleaned_data
class CustomUserCreationForm(UserCreationForm):
"""
A form that creates a user, with no privileges, from the given email and
password.
"""
def __init__(self, *args, **kargs):
super(CustomUserCreationForm, self).__init__(*args, **kargs)
del self.fields['username']
class Meta:
model = CustomUser
fields = ("email",)
admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
from .models import CustomUser
from .forms import CustomUserCreationForm
class CustomUserAdmin(admin.ModelAdmin):
form = CustomUserCreationForm
admin.site.register(CustomUser, CustomUserAdmin)
backends.py:
from models import CustomUser
class CustomUserAuth(object):
def authenticate(self, username=None, password=None):
try:
user = CustomUser.objects.get(email=username)
if user.check_password(password):
return user
except CustomUser.DoesNotExist:
return None
def get_user(self, user_id):
try:
user = CustomUser.objects.get(pk=user_id)
if user.is_active:
return user
return None
except CustomUser.DoesNotExist:
return None
Remove django.contrib.customuser and django.contrib.auth from your INSTALLED_APPS. There is no customuser application under django.contrib package, and auth can be omitted (to avoid potential name colission).
Furthermore, I suggest you re-read the Django docs on auth customization. Most of the changes are optional, and your code should be simplified by re-using the base classes, unless your methods vary of course.
The docs also mentions that for swapping User models, you are required to update settings to AUTH_USER_MODEL = 'customuser.CustomUser'.