Hello Friends,

I am trying to extend user model to setup email as username. Everything 
works find when I create new user using django admin I get error  “Manager 
isn't available; User has been swapped” when try to create user using 
signup view. 

There is very few articles on this error. Any help would be appreciated. 
Also, the login thing is working perfectly. 

I have defined 


AUTH_USER_MODEL = 'user_management.CustomUser'

AUTHENTICATION_BACKENDS = ('user_management.manager.CustomUserAuth',)


My code is as follows

----------------------------------
Signup view
--------------------------------

def signup(request):

    form= CustomUserCreationForm(request.POST or None)
    
    if request.POST and form.is_valid():
        print "test2"
        form.save(commit=False)
        email=form.cleaned_data['email']
        password=form.cleaned_data['password1']
        CustomUser.objects.create_user(email=email,password=password)
        user=CustomUser.objects.get(email=email)
        user.is_active=0
        user.save()
        print email
        
        salt = 
hashlib.sha1(str(random.random())).hexdigest()[:5]            
        activation_key = hashlib.sha1(salt+email).hexdigest()            
        key_expires = timezone.datetime.today() + timedelta(days=2)
        
       
        
        if user:
            return HttpResponseRedirect('/signup_success')
    
    return render(request,'user_management/signup.html',{'form':form})

----------------------------------------------------------------------------------------------------------------

model.py for user_management app 
--------------------------------------------------------------------------------------------------------------------

class CustomUserManager(BaseUserManager):
    def _create_user(self,email,password,is_staff,is_superuser, 
**extra_fields):

        if not email:
            raise ValueError('The given email must be set')
        
        email=self.normalize_email(email)
        user= self.model(email=email,
                         is_staff=is_staff,
                         is_active = True,
                         is_superuser =is_superuser,
                         last_login=timezone.now(),
                         date_joined=timezone.now(),
                        **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user
    
    def create_user(self, email,password=None,**extra_fields):
        return self._create_user(email,password,False,False,**extra_fields)
    
    def create_superuser(self, email,password,**extra_fields):
        return self._create_user(email,password,True,True,**extra_fields)
    
class CustomUser(AbstractBaseUser,PermissionsMixin):
    username =models.CharField(max_length =255, unique = True,blank = 
True,null= True)
    email =models.EmailField(blank=False, unique =True)
    date_joined  = models.DateTimeField(_('date joined'), default=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)
   
    USERNAME_FIELD ='email'
    REQUIRED_FIELD =['user_name','date_joined']
    
    objects=CustomUserManager()
    
    class Meta:
        verbose_name=_('user')
        verbose_name_plural=_('users')
    
    def get_absolute_url(self):
        return "/user/%s" %urlquote(self.email)
    
    def get_full_name(self):
      
        a=UserProfile.objects.get(email_id=self.id)
        self.first_name=a.first_name
        self.last_name= a.last_name
        if not self.first_name and not self.last_name:
            full_name =self.email
        else:
            full_name = '%s %s' %(self.first_name,self.last_name)
        return full_name.strip()

    def get_short_name(self):
        self.first_name='a'
        return self.first_name
    
    def email_user(self,subject,message,from_email=None):
        send_mail(subject,message,from_email,[self.email])


        #code
-------------------------------------------------------------------------------------------------------------
manager.py
-------------------------------------------------------------------------------------------------------------


from models import CustomUser
from models import CustomUserManager

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
         
 
-----------------------------------------------------------------------------------------
form.py 
----------------------------------------------------------------------------------------------
from django.contrib.auth import authenticate
from django.contrib.auth import get_user_model

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']
    def clean(self):
            password1=self.cleaned_data.get('password1')
            password2=self.cleaned_data.get('password2')
            username=self.cleaned_data.get('email')
            print username
            try:
                user=CustomUser.objects.get(email=username)
            except:
                user=None
            if user:
                raise forms.ValidationError("Email address already 
registered with us")
            
            if password1!=password2:
                raise forms.ValidationError("Both password should be same")
            
        
            class Meta:
                model = CustomUser
                #fields = "__all__"
                fields = ("email",)
        

class CustomUserChangeForm(UserChangeForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """

    def __init__(self, *args, **kargs):
        super(CustomUserChangeForm, self).__init__(*args, **kargs)
        #del self.fields['username']

    
    class Meta:
        model = CustomUser
        fields = "__all__"
        

        
class UserLoginForm(forms.Form):
    username = forms.CharField()
    password= forms.CharField(widget=forms.PasswordInput)
    
    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        #user = authenticate(username=username, password=password)
        try:
            user=CustomUser.objects.get(email=username)
        except:
            user=None
        if not user:
            raise forms.ValidationError("Email not registered with us.")
        if not user.is_active and user.check_password(password):
            raise forms.ValidationError("Account is inactive, please check 
your mail for activation email")
        else:
            if not user.check_password(password):
                raise forms.ValidationError("Incorrect password")
        #if not user:
        #    raise forms.ValidationError("Sorry, that login was invalid. 
Please try again.")
        return self.cleaned_data
        
    

    def login(self, request):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        user = authenticate(username=username, password=password)
        return user

I hope I included enough for someone to help me. Not sure but I hardly got 
any help from this group.

Regards,
Sarfaraz Ahmed

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/1933e858-df4b-4f8a-a347-ad03de3c433c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to