Django/ user registration by email activation - in class based view - django

I'm trying to register users but not making them active until they activate their accounts withe the email activation link but..
I get a 'UserBase' object has no attribute 'email_user' error
and when changing it to 'email' instead of 'user_email' i get a
'str' object is not callable error
I get the activation link from the error page and it works when trying it on another tab (makes account active)
View:
class UserReigster(CreateView):
model = UserBase
form_class = Registration
template_name = 'account/registration/registration.html'
success_url = '/'
def form_valid(self, form):
user = form.save()
# Email Activation Setup
current_site = get_current_site(self.request)
subject = 'Activate Your Account'
message = render_to_string('account/registration/account_activation_email.html', {
'user':user,
'domain':current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token':account_activation_token.make_token(user),
})
user.email_user(subject=subject, message=message)
# Success registration message
messages.add_message(
self.request,
messages.SUCCESS,
'Check Your Email For Account Activation Link'
)
return super().form_valid(form)
def account_activation(request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = UserBase.objects.get(pk=uid)
except():
pass
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
login(request, user)
return redirect('account:dashboard')
else:
return render(request, 'account/registration/activation_invalid.html')
models:
class CustomAccountManager(BaseUserManager):
def create_superuser(self, email, user_name, password, **other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_active', True)
if other_fields.get('is_staff') is not True:
raise ValueError(
'Superuser must be assigned to is_staff=True.')
if other_fields.get('is_superuser') is not True:
raise ValueError(
'Superuser must be assigned to is_superuser=True.')
return self.create_user(email, user_name, password, **other_fields)
def create_user(self, email, user_name, password, **other_fields):
if not email:
raise ValueError(_('You must provide an email address'))
email = self.normalize_email(email)
user = self.model(email=email, user_name=user_name, **other_fields)
user.set_password(password)
user.save()
return user
class UserBase(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
user_name = models.CharField(max_length=150, unique=True)
first_name = models.CharField(max_length=150, blank=True)
about = models.TextField(_('about'), max_length=500, blank=True)
# Delivery Details
country = CountryField()
phone_number = models.CharField(max_length=15, blank=True)
postcode = models.CharField(max_length=12, blank=True)
address_line_1 = models.CharField(max_length=150, blank=True)
address_line_2 = models.CharField(max_length=150, blank=True)
town_city = models.CharField(max_length=150, blank=True)
# User Status
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
# Custom Manager
objects = CustomAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['user_name']
class Meta:
verbose_name = 'Account'
verbose_name_plural = 'Accounts'
def __str__(self):
return self.user_name

Using AbstractbaseUser in custom User you deleted the method email_user
You need to create it again in the custom user model:
def email_user(self, *args, **kwargs):
send_mail(
'{}'.format(args[0]),
'{}'.format(args[1]),
'{}'.format(args[2]),
[self.email],
fail_silently=False,
)

Related

Error in Django Model and Serializer - (1048, "Column 'dso_id' cannot be null")

I am trying to create a user profile, I feel i have everything correct but still it doesn't register.
You see my codebase below, please help
What i did:
Models.py:
class UserManager(BaseUserManager):
def create_user(self, username, email, name, address,roleId,customerId,dso password=None,):
if username is None:
raise TypeError('User should have a userame')
if email is None:
raise TypeError('Users should have a Email')
user = self.model(username=username , email = self.normalize_email(email))
user.set_password(password)
user.save()
return user
def create_superuser(self, username, email, password=None):
if password is None:
raise TypeError('User should have a password')
user=self.create_user(username,email,password,)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class User(models.Model):
dso = models.ForeignKey(Dso,related_name='dso',default=NULL,blank=False,on_delete=models.CASCADE)
name = models.CharField(max_length=70, blank=False, default='')
email = models.EmailField(max_length=70, blank=False, default='')
password = models.CharField(max_length=70, blank=False, default='')
address = models.CharField(max_length=70, blank=False, default='')
roleId = models.IntegerField(blank=False, default='1')
isActive = models.BooleanField(blank=False, default=True)
customerId = models.CharField(max_length=70, blank=False, default='')
dateJoined = models.DateTimeField(auto_now_add=False, blank=False, default=NULL)
#property
def energy_data(self):
energydata = EnergyData.objects.filter(customerId=self.customerId).first()
return energydata
Serializers.py:
class RegisterSerializer(serializers.ModelSerializer):
password = serializers.CharField(max_length = 68, min_length=6, write_only = True)
class Meta:
model=User
fields=['email','username','password','name','address','customerId',
'dso', 'roleId']
def validate(self, attrs):
email = attrs.get('email', '')
username = attrs.get('username', '')
if not len(username) >= 4:
raise serializers.ValidationError('Username must be morethan 4 letters or characters')
return attrs
def create(self, validated_data):
return User.objects.create_user(**validated_data)
Views.py:
class RegisterView(generics.GenericAPIView):
serializer_class= RegisterSerializer
def post(self, request):
user = request.data
serializer = self.serializer_class(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
user_data = serializer.data
user= User.objects.get(email=user_data['email'])
token = RefreshToken.for_user(user).access_token
current_site = get_current_site(request).domain
relativeLink = reverse('email-verify')
absolute_url = 'http://'+current_site+relativeLink+"?token="+str(token)
email_body= 'Hi '+ user.username + ' Use this link below to verify your email \n'+ absolute_url
data = {'email_subject': 'Verify Your Email', 'email_body': email_body , 'to_email': user.email}
Util.send_email(data)
return Response(user_data, status = status.HTTP_201_CREATED)
URL Path:
path('register/', RegisterView.as_view(), name="register" )
When i do this and try to test i get the error, '(1048, "Column 'dso_id' cannot be null")'
Please kindly help as i am new to django rest framework.
error thrown from this line in User Model
dso = models.ForeignKey(Dso,related_name='dso',default=NULL,blank=False,on_delete=models.CASCADE)
you set default NULL while don't set null and blank fields True
so change to this or remove default=NULL(None)
dso = models.ForeignKey(Dso,related_name='dso',default=NULL, blank=True, null=True, on_delete=models.CASCADE)
also you should not useNULL in python, use None replace that

Not hashing password. Unexpected keyword argument 'password2'

I have three different questions. They're all related to each other.
1 - I get an error when I add password2 or confirm_password field.
Got a `TypeError` when calling `CustomUser.objects.create()`.
This may be because you have a writable field on the serializer class that is not a valid argument to `CustomUser.objects.create()`.
You may need to make the field read-only, or override the UserCreateSerializer.create() method to handle this correctly.
TypeError: CustomUser() got an unexpected keyword argument 'confirm_password'
2 - Without any validate when I only have password field. I am not getting any errors but passwords are not hashed.
3 - When I want to create user using shell. Even if I leave all the fields blank, I can create an empty user without any errors.
Custom User Manager
class CustomUserManager(BaseUserManager):
def create_user(self, email, password=None,**kwargs):
if not email:
raise ValueError('Email is required!')
user = self.model(
email = self.normalize_email(email),
**kwargs,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password=None, **kwargs):
user = self.create_user(
email,
password=password,
**kwargs
)
user.is_admin = True
user.save(using=self._db)
return user
Custom User
class CustomUser(AbstractBaseUser):
email = models.EmailField(_('Email'), max_length=50, unique=True)
username = models.CharField(_('Username'),max_length=50)
first_name = models.CharField(_('First Name'),max_length=50)
middle_name = models.CharField(_('Middle Name'),max_length=50, blank=True, null=True)
last_name = models.CharField(_('Last Name'),max_length=50)
desc = models.TextField(_('Description'), blank=True, default='Nothing here.')
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = CustomUserManager()
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = []
def __str__(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_staff(self):
"Is the user a member of staff?"
return self.is_admin
User Serializer
User = get_user_model()
class UserCreateSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=True, validators =[validators.UniqueValidator(queryset=User.objects.all())])
password = serializers.CharField(write_only=True, required=True, validators=[validate_password])
confirm_password = serializers.CharField(write_only=True, required=True)
class Meta:
model = User
fields = [
'email',
'username',
'first_name',
'middle_name',
'last_name',
'password',
'confirm_password',
]
def validate(self, data):
email = data['email']
print(data)
user_qs = User.objects.filter(email=email)
if user_qs.exists():
raise serializers.ValidationError('This user has already registered!')
if data['password'] != data['confirm_password']:
raise serializers.ValidationError('Passwords didn\'t match!')
elif data.get('password') == data.get('confirm_password'):
data['password'] = make_password(
data.get('password')
)
data.pop('confirm_password', None)
return data
def create(self, validated_data):
username = validated_data['username']
email = validated_data['email']
first_name = validated_data['first_name']
middle_name = validated_data['middle_name']
last_name = validated_data['last_name']
user = User.objects.create(
username = username,
email = email,
first_name=first_name,
middle_name=middle_name,
last_name=last_name,
)
user.set_password(validated_data['password'])
user.save()
return user

Django Custom User Model is not using The model manager while creating normal users

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)

How to use post_save signal with custom user model extended with AbstractBaseUser

There are two apps in my ecommerce website and i have been following a particular tutorial on youtube. In the course, the guy used django-allauth package for login purposes. I followed the course along but I created custom user model exending AbstracBaseUser class in account app.
I created another app called product where I handled all the ecommerce logics.
Here's the code:
models.py (account)
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, first_name, last_name, gstin_no, phone_no, password=None):
if not email:
raise ValueError("Users must have an email address")
if not username:
raise ValueError("Users must have a username")
if not first_name:
raise ValueError("Users must have First Name")
if not last_name:
raise ValueError("Users must have Last Name")
if not gstin_no:
raise ValueError("Users must have a valid GSTIN Number")
if not phone_no:
raise ValueError("Users must have a valid Phone Number")
user = self.model(
email=self.normalize_email(email),
username=username,
first_name=first_name,
last_name=last_name,
gstin_no=gstin_no,
phone_no=phone_no,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, first_name, last_name, gstin_no, phone_no, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
first_name=first_name,
last_name=last_name,
gstin_no=gstin_no,
phone_no=phone_no,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
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)
first_name = models.CharField(verbose_name="first name", max_length=20)
last_name = models.CharField(verbose_name="last name", max_length=20)
gstin_no = models.CharField(verbose_name='gstin no', max_length=15, unique=True)
phone_no = models.BigIntegerField(unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'gstin_no', 'phone_no', ]
objects = MyAccountManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
models.py (product)
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
stripe_customer_id = models.CharField(max_length=50, blank=True, null=True)
one_click_purchasing = models.BooleanField()
def __str__(self):
return self.user.username
def userprofile_receiver(sender, instance, created, *args, **kwargs):
if created:
userprofile = UserProfile.objects.create(user=instance)
post_save.connect(userprofile_receiver, sender=settings.AUTH_USER_MODEL)
views.py (product)
class PaymentView(LoginRequiredMixin, View):
def get(self, *args, **kwargs):
order = Order.objects.get(user=self.request.user, ordered=False)
if order.billing_address:
context = {
'order': order,
'DISPLAY_COUPON_FORM': False
}
userprofile = self.request.user.userprofile
if userprofile.one_click_purchasing:
#fetch the user's card list
cards = stripe.Customer.list_sources(
userprofile.stripe_customer_id,
limit = 3,
object = 'card'
)
card_list = cards['data']
if len(card_list) > 0:
# update the card with the default card
context.update({
'card': card_list[0]
})
return render(self.request, 'product/payment.html', context)
else:
messages.warning(self.request, "You have not added a billing address.")
return redirect("checkout")
The error I am getting is:
RelatedObjectDoesNotExist at /payment/stripe/
Account has no userprofile.
How can I get this working. I am not able to get the concept here about what's wrong.
Go to django admin and check is that userprofile created for that user.If not, Then it is possible you have added user before adding this signal functionality. create new user and check userprofile. If still not created. There is something wrong with your signal.

Django UserCreationForm

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