I am working with user authentication system where I created a user registration model using AbstractBaseUser. then I create super User using terminal . But when I go the admin and write email and password there . It gives me the error that: 'User' object has no attribute 'is_staff'
My models.py file is:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser,BaseUserManager
SUBJECT_CHOICES = (
('math','Math'),
('physics','Physics'),
('chemistry','Chemistry'),
)
class UserManager(BaseUserManager):
def create_user(self, email, full_name=None, password=None, is_staff=False, is_admin=False):
if not email:
raise ValueError("User must have an email")
if not password:
raise ValueError("User must have a password")
user_obj = self.model(email=self.normalize_email(email), full_name=full_name)
user_obj.set_password(password)
user_obj.staff = is_staff
user_obj.admin = is_admin
user_obj.save(using=self._db)
return user_obj
def create_staffuser(self,email,full_name=None,password=None):
user = self.create_user(email, full_name=full_name,password=password)
return user
def create_superuser(self,email, full_name=None,password=None):
user = self.create_user(email, full_name=full_name, password=password)
return user
class User(AbstractBaseUser):
full_name = models.CharField(max_length=255, blank=True, null=True)
sur_name = models.CharField(max_length=255, blank=True, null=True)
email = models.EmailField(max_length=255 ,unique=True)
choose_subject = models.CharField(choices=SUBJECT_CHOICES , max_length=100)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
time_stamp = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
object = UserManager()
def __str__(self):
return self.full_name
my forms.py file is:
class RegisterForm(forms.ModelForm): # A form for creation new user included all all the required fields including repeated password
password1 = forms.CharField(label='Enter Password' , widget=forms.PasswordInput )
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = User
fields=('full_name','sur_name','email','choose_subject')
def clean_password2(self): # check that two password entries match or not
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("password dont match")
return password2
def save(self , commit=True): #save the provided password in hashed format
user = super(RegisterForm , self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
#user.active = False #send confirmation email
if commit:
user.save()
return user
my views.py is:
class RegisterView(CreateView):
form_class = RegisterForm
template_name = "users/register.html"
success_url = '/register'
Thank You.
There are two ways to resolve this problem
Number one: create property method into your user model:
#property
def is_staff(self):
return self.staff
Number two: rename "staff" field to "is_staff", it would be righter
It should be
is_staff
but not staff...
You can have it working if you type staff or change the model field to
is_staff.
Related
I'm trying to create a user from the Django rest framework's ModelViewset. (However, I've also tried to do the same with regular Django's model form. In both cases, the CustomUser model is not using the create_user function from the Model manager.
My codes are as follows:
Model Manager
class CustomUserManager(BaseUserManager):
def create_user(self, email, phone, full_name, **other_fields):
email = self.normalize_email(email)
if not email:
raise ValueError("User must have an email")
if not full_name:
raise ValueError("User must have a full name")
if not phone:
raise ValueError("User must have a phone number")
user = self.model(
email=self.normalize_email(email),
phone=phone,
full_name=full_name,
is_active=True,
)
other_fields.setdefault('is_active', True)
user.set_password(phone)
user.save(using=self._db)
return user
def create_superuser(self, email, phone, full_name, password=None, **other_fields):
if not email:
raise ValueError("User must have an email")
if not password:
raise ValueError("User must have a password")
if not full_name:
raise ValueError("User must have a full name")
if not phone:
raise ValueError("User must have a phone number")
user = self.model(
email=self.normalize_email(email),
full_name = full_name,
phone = phone
)
user.set_password(password) # change password to hash
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_active', True)
user.save(using=self._db)
return user
Model:
class CustomUserModel(AbstractBaseUser, PermissionsMixin, AbstractModel):
email = models.EmailField(unique=True)
username = models.CharField( max_length=150, unique=True, null=True, blank=True)
phone = PhoneNumberField(unique=True)
full_name = models.CharField(max_length=50, null=True, blank=True)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
objects = CustomUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['phone', 'full_name']
class Meta:
verbose_name = 'User'
verbose_name_plural = 'Users'
def __str__(self):
return f'{self.username} - {self.email}'
def save(self, *args, **kwargs):
if not self.username:
uid = str(uuid4()).split('-')[1].upper()
today = str(date.today()).replace('-', '').swapcase()
splitted_uname = self.full_name.split(' ')[0][:2].upper()
self.username = f'{splitted_uname}-{uid}{today}'
super(CustomUserModel, self).save(*args, **kwargs)
Django REST Framework's ViewSet
class UserBaseViewSet(viewsets.ModelViewSet):
allowed_methods = ('GET', 'POST', 'PATCH')
serializer_class = serializers.UserBaseListSerializer
queryset = CustomUserModel.objects.all()
permission_classes = [IsProfileOwnerOrReadOnly, ]
lookup_field = 'username'
def get_serializer_class(self):
if self.action == 'retrieve':
return serializers.UserBaseDetailSerializer
return super().get_serializer_class()
While creating superusers from the command line it works perfectly.
What am I missing in this process?
I debug the process but the model class doesn't users the create_user function of the manager in any way.
You will have to override create of UserBaseListSerializer to call the manager's create_user:
class UserBaseListSerializer(serializers.ModelSerializer):
...
def create(self, validated_data):
return CustomUserModel.objects.create_user(**validated_data)
When I call the api/seller/register api, the fields appear are username, password1 and password2. I want these removed and only want simple password, email and phone_num.
How to remove this?
I am trying to make a seller registration using RegisterSerializer. I tried with ModelSerailzers and provided fields as I want but this will lead to me the error saying save() only takes 1 argument.So, I just want these unnecessary fields removed using RegisterSerializer.
My model:
class CustomUserManager(BaseUserManager):
"""
Custom user model manager with email as the unique identifier
"""
def create_user(self, first_name, last_name, email, password, **extra_fields):
"""
Create user with the given email and password.
"""
if not email:
raise ValueError("The email must be set")
first_name = first_name.capitalize()
last_name = last_name.capitalize()
email = self.normalize_email(email)
user = self.model(
first_name=first_name, last_name=last_name, email=email, **extra_fields
)
user.set_password(password)
user.save()
return user
def create_superuser(self, first_name, last_name, email, password, **extra_fields):
"""
Create 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(first_name, last_name, email, password, **extra_fields)
class CustomUser(AbstractUser):
username = models.CharField(max_length=255,blank=False)
first_name = models.CharField(max_length=255, verbose_name="First name")
last_name = models.CharField(max_length=255, verbose_name="Last name")
email = models.EmailField(unique=True)
is_seller = models.BooleanField(default=False)
is_customer = models.BooleanField(default=False)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["first_name", "last_name"]
objects = CustomUserManager()
def __str__(self):
return self.email
My serializer:
class SellerRegisterSerializer(RegisterSerializer):
seller = serializers.PrimaryKeyRelatedField(read_only=True,)
# username = serializers.CharField(required=True)
phone_num = serializers.CharField(required=False)
# class Meta:
# model = User
# fields = ['seller','email', 'phone_num', 'first_name', 'last_name', 'password']
def get_cleaned_data(self):
data = super(SellerRegisterSerializer, self).get_cleaned_data()
extra_data = {
'phone_num': self.validated_data.get('phone_num', ''),
}
data.update(extra_data)
return data
def save(self, request, **kwargs):
user = super(SellerRegisterSerializer, self).save(request)
# user = super().save(is_seller=True)
user.is_seller = True
user.save()
seller = Seller(seller=user,
phone_num=self.cleaned_data.get('phone_num'))
seller.save()
return user
My view:
class SellerRegisterView(RegisterView):
serializer_class = SellerRegisterSerializer
I followed CodingEntrepreneurs tutorial on Custom Users and extended it to have 3 types of users: school, parent and vendor.
I have created view, form for each type of user.
In forms.py I have
class ParentSignUpForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta():
model = User
fields = ('email', )
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
user = super(ParentSignUpForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.is_parent = True
user.save()
return user
I try to change is_parent attribute from False to True. However, error is:
File "/home/azamat/dev/dj_test/src/accounts/forms.py", line 137, in save
user.is_parent = True
AttributeError: can't set attribute
How to solve this issue? Or any better way to save users with different types?
UPDATE:
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager
)
class UserManager(BaseUserManager):
def create_user(self, email, password=None, is_staff=False, is_admin=False, is_active=True, is_parent=False, is_school=False, is_vendor=False):
if not email:
raise ValueError("Users must have an email address")
if not password:
raise ValueError("Users must have a password")
user_obj = self.model(
email = self.normalize_email(email)
)
user_obj.set_password(password) # change user password
user_obj.parent = is_parent
user_obj.school = is_school
user_obj.vendor = is_vendor
user_obj.active = is_active
user_obj.staff = is_staff
user_obj.admin = is_admin
user_obj.save(using=self._db)
return user_obj
def create_parentuser(self, email, password=None):
user = self.create_user(
email,
password=password,
is_parent=True
)
return user
def create_schooluser(self, email, password=None):
user = self.create_user(
email,
password=password,
is_school=True
)
return user
def create_vendoruser(self, email, password=None):
user = self.create_user(
email,
password=password,
is_vendor=True
)
return user
def create_staffuser(self, email, password=None):
user = self.create_user(
email,
password=password,
is_staff=True
)
return user
def create_superuser(self, email, password=None):
user = self.create_user(
email,
password=password,
is_staff=True,
is_admin=True,
)
return user
class User(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
active = models.BooleanField(default=True) # can login
parent = models.BooleanField(default=False) # parent user
school = models.BooleanField(default=False) # school admin user
vendor = models.BooleanField(default=False) # vendor user
staff = models.BooleanField(default=False) # staff user non superuser
admin = models.BooleanField(default=False) # superuser
timestamp = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email' #username
objects = UserManager()
def __str__(self):
return self.email
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_parent(self):
return self.parent
#property
def is_school(self):
return self.school
#property
def is_vendor(self):
return self.is_vendor
#property
def is_active(self):
return self.active
#property
def is_staff(self):
return self.staff
#property
def is_admin(self):
return self.admin
How I solved it:
I have added REQUIRED_FIELDS = ['parent', 'school', 'vendor' ] to my model.py So now on my registration page, I have 3 check buttons where I can select a needed type of user.
In forms.py I left only RegisterForm and deleted register forms for my 3 user types
class RegisterForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email', **'parent', 'school', 'vendor'**) #'added 3 fields',)
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(RegisterForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
# user.active = False # send confirmation email
if commit:
user.save()
return user
So I'm making a custom user model. This is what I'am following Here. I have been pretty much following the tutorial but still I cant make it done.
Error: RegisterForm() missing 1 required positional argument: 'request'.
here's my code.
forms.py
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import User
class UserAdminCreationForm(forms.ModelForm):
"""
A form for creating new users. Includes all the required
fields, plus a repeated password.
"""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email',)
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserAdminCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserAdminChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = ('email', 'password', 'active', 'admin')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
class LoginForm(forms.ModelForm):
email = forms.EmailField(label='Email')
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email', 'password',)
widgets = {
'email' : forms.EmailInput(
attrs={'class':'form-control', 'place_holder': '', }),
'password' : forms.PasswordInput(
attrs={'class':'form-control' }),
}
class RegisterForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email',)
def clean_email(self):
email = self.cleaned_data.get('email')
qs = User.objects.filter(email=email)
if qs.exists():
raise forms.ValidationError("email is taken")
return email
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
models.py
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class UserManager(BaseUserManager):
def create_user(self, email, full_name, password=None, is_staff=False, is_active=True, is_admin=False):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Users must have an email address')
if not full_name:
raise ValueError('Users must have an full name')
if not password:
raise ValueError('Users must have a password')
user = self.model(
email=self.normalize_email(email),
)
user.full_name = full_name
user.set_password(password)
user.staff = is_staff
user.admin = is_admin
user.active = is_active
user.save(using=self._db)
return user
def create_staffuser(self, email, password):
"""
Creates and saves a staff user with the given email and password.
"""
user = self.create_user(
email,
password=password,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, full_name, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.model(
email=self.normalize_email(email)
)
user.full_name = full_name
user.set_password(password)
user.full_name = full_name
user.staff = True
user.admin = True
user.save(using=self._db)
return user
# Create your models here.
class User(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
full_name = models.CharField(max_length=255, null=True, blank=True)
active = models.BooleanField(default=True) # to login
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
created_date = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['full_name'] # Email & Password are required by default.
objects = UserManager()
def __str__(self):
return self.email
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 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?"
return self.staff
#property
def is_admin(self):
"Is the user a admin member?"
return self.admin
#property
def is_active(self):
"Is the user active?"
return self.active
class Account_type(models.Model):
name = models.CharField(max_length=50, null=True, blank=True)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
account_type = models.ForeignKey(Account_type, on_delete=models.CASCADE)
register.html
from django.shortcuts import render, redirect
from . forms import RegisterForm, LoginForm
# Create your views here.
def RegisterForm(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
else:
form = RegisterForm()
context = {
'form' : form
}
return render(request, 'account/register.html', context)
The view logic is simple as you can see. Just saving up the request into the database. The tutorial itself did not tell anything about the view for login and register.
So, What am I doing wrong here.
Thank you
The problem is that your view RegisterForm has the same name as your form, hence if you call RegisterForm in your view, it will resolve to the view function, and make a recursive call.
Normally (top-level) functions are written in snake_case, hence you can rewrite it to register_form, or even better register (since it is not a form at all):
from django.shortcuts import render, redirect
from . forms import RegisterForm, LoginForm
# Create your views here.
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
return redirect('some-view-name')
else:
form = RegisterForm()
context = {
'form' : form
}
return render(request, 'account/register.html', context)
Normally a successful POST request results in a redirect to implement the Post/Redirect/Get pattern [wiki]. So I strongly advise you to use redirect(..) [Django-doc] and replace some-view-name with the name of a view to which you want to redirect.
We have built our platform using django and created a custom user model for our usage.
Up until now our platform was invite only and now we want to open the invites to everyone.
I've modified our custom form and view for the user registration and everything is working, but we're facing one issue. When sending an invite if the user's email is not registered on our platform we create a new user for him and set a boolean to mark him as not active. When coming in with the invite everything works OK, but if the user goes directly to our page and opens the registration form we get the error that a user with this email already exists.
We're extending the CreateView and the UserCreationForm to implement our custom registration form, so I'm guessing I must override one of the methods in these classes but not quite sure which one, I've tried with the save method of the UserCreationForm but it doesn't seem to work, it pops up the error messages without going into that method.
Any ideas on how I could do this? The implementation required would be that we look if a user with that email exists and he is inactive then save the registration form elements and set him to active, otherwise just show the error message.
class CustomUserCreationForm(UserCreationForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
super(CustomUserCreationForm, self).__init__(*args,**kwargs)
self.fields.pop('username')
class Meta:
model = DealCircleUser
#fields = ('email', 'dob', 'first_name', 'last_name')
fields = ('email', 'first_name', 'last_name')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError ("Passwords don't match")
return password2
def save(self, commit=True):
exits = DealCircleUser.objects.filter(email=self.cleaned_data["email"]).exists()
if exits:
print('We have the user')
user = DealCircleUser.objects.get(email=self.cleaned_data["email"])
else:
print('No user found')
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
#check if there is a user already created with this
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
And the view is:
class RegisterUserView(CreateView):
model = DealCircleUser
template_name = 'register.html'
form_class = CustomUserCreationForm
success_url = reverse_lazy('frontend_profile')
invitation = None
def get_form(self, form_class):
code = self.request.GET.get('code')
if code:
self.invitation = Invitation.validate_code(code)
if not self.request.user.is_anonymous():
form_class = InputEmailForm
self.object = self.request.user
form = super(RegisterUserView, self).get_form(form_class)
form.fields['email'].widget.attrs['class'] = 'form-control'
if self.request.user.is_anonymous():
if self.invitation and self.invitation.email:
form.fields['email'].widget.attrs['readonly'] = True
form.fields['first_name'].widget.attrs['class'] = 'form-control'
form.fields['last_name'].widget.attrs['class'] = 'form-control'
form.fields['password1'].widget.attrs['class'] = 'form-control'
form.fields['password2'].widget.attrs['class'] = 'form-control'
if self.invitation:
form.initial['email'] = self.invitation.email
return form
def get_context_data(self, **kwargs):
ret = super(RegisterUserView, self).get_context_data(**kwargs)
ret['twitterEnabled'] = settings.ENABLE_TWITTER
if self.request.user.is_anonymous():
#if not self.invitation or self.invitation.is_used():
# ret['invalid_code'] = True
# return ret
if self.invitation and self.invitation.is_used():
ret['invalid_code'] = True
return ret
ret['code'] = self.request.GET.get('code')
return ret
def form_valid(self, form):
ret = super(RegisterUserView, self).form_valid(form)
if type(ret) == HttpResponseRedirect:
if self.invitation:
self.invitation.status = Invitation.STATUS_REGISTERED
self.invitation.save()
messages.add_message(self.request, messages.SUCCESS,
_('Your account has been created. Welcome to DealCircle!'))
else:
messages.add_message(self.request, messages.SUCCESS, _('Your account has been updated successfully.'))
user = authenticate(email=form.cleaned_data.get('email'), password=form.cleaned_data.get('password1'))
if user and user.is_active:
login(self.request, user)
return ret
def get_success_url(self):
if self.invitation and self.invitation.deal:
return reverse('frontend_invitation_response', args=(self.invitation.code,))
else:
return reverse('frontend_profile')
def linkedin_info(user):
import oauth2 as oauth
consumer = oauth.Consumer(settings.SOCIAL_AUTH_LINKEDIN_KEY, settings.SOCIAL_AUTH_LINKEDIN_SECRET)
access_token = oauth.Token(key=user.linkedin_token, secret=user.linkedin_token_secret)
client = oauth.Client(consumer, access_token)
resp, content = client.request("http://api.linkedin.com/v1/people/~:(first-name,last-name,phone-numbers,picture-urls::(original))?format=json", "GET", "")
return resp, content
The custom user manager is this:
class DealCircleUserManager(BaseUserManager):
def create_user(self, email=None, password=None, **extra_fields):
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = UserManager.normalize_email(email)
user = self.model(email=email,
is_staff=False, is_active=True, is_superuser=False,
last_login=now, date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
from postman.models import AddressBook
AddressBook.objects.get_or_create(user=user)
return user
def create_superuser(self, email, password, **extra_fields):
u = self.create_user(email, password, **extra_fields)
u.is_staff = True
u.is_active = True
u.is_superuser = True
u.save(using=self._db)
from postman.models import AddressBook
AddressBook.objects.get_or_create(user=u)
return u
And the model is this:
class DealCircleUser(AbstractBaseUser, PermissionsMixin):
USERNAME_FIELD = 'email'
AVATAR_STORAGE_URL = 'https://%s.s3.amazonaws.com/%s'
avatar = models.ImageField(storage=s3, upload_to="users", null=True, blank=True)
avatar_thumb = ImageSpecField(cachefile_storage=s3, source='avatar',
processors=[ResizeToFill(*settings.THUMB_AVATAR)],
format='JPEG',
options={'quality': 60})
avatar_square_thumb = ImageSpecField(cachefile_storage=s3, source='avatar',
processors=[SmartResize(*settings.THUMB_AVATAR_SQUARE)],
format='JPEG',
options={'quality': 60})
email = models.EmailField(max_length=254, unique=True)
address = models.CharField(max_length=254, blank=True)
postal_code = models.CharField(max_length=100, blank=True)
city = models.CharField(max_length=254, blank=True)
country = models.ForeignKey(Country, verbose_name='country', null=True, blank=True)
phone = models.CharField(max_length=30, blank=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
dob = models.DateField(null=True, blank=True)
bio = models.TextField(blank=True)
twitter_token = models.CharField(max_length=100, null=True, blank=True)
twitter_token_secret = models.CharField(max_length=100, null=True, blank=True)
linkedin_token = models.CharField(max_length=100, null=True, blank=True)
linkedin_token_secret = models.CharField(max_length=100, null=True, blank=True)
linkedin_connection_hash = models.CharField(max_length=64, blank=True)
google_access_token = jsonfield.JSONField(null=True, blank=True)
google_user_extras = jsonfield.JSONField(null=True, blank=True)
company = models.ForeignKey(Company, verbose_name='company', blank=True, null=True)
date_joined = models.DateField(null=True)
first_visit = models.BooleanField(default=True)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin '
'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 = DealCircleUserManager()
def get_avatar_from_url(self, url):
try:
self.avatar.save(os.path.basename(url), ContentFile(urllib2.urlopen(url).read()))
self.save()
return True
except Exception, e:
return False
def get_avatar_url(self):
return self.AVATAR_STORAGE_URL % (settings.BOTO_S3_BUCKET, self.avatar)
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def get_dealinvestor(self, deal):
return self.dealinvestor_set.get(deal=deal)
def is_email_valid(self):
try:
validate_email(self.email)
return True
except:
return False
def disable_first_visit(self):
self.first_visit = False
self.save()
I think that your form does not validate :
you should take a look at the clean method(s) of the UserCreationForm and then do something like this (didn't tested) :
def clean_email(self):
"""
First checking if the there is an invited user (User with same email exists and active==False ), if so validate the email.
If the user exists and is active that means that the email is already in use, we raise a ValidationError
If none of the above are True, the user does not exists at all, we should create it.
"""
email = self.cleaned_data['email']
if DealCircleUser.objects.filter(email=self.cleaned_data["email"], active=False).exists():
return email
elif DealCircleUser.objects.filter(email=self.cleaned_data["email"], active=True).exists():
raise forms.ValidationError(u'Email "%s" is already in use.' % email)
return email