I am using django 1.7 python 3.4 I have created a custom MyUser class which is derived from AbstractBaseUser. Now, when I try to register a user, I am getting the error 'AnonymousUser' object has no attribute 'backend'. views.py
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if not form.is_valid():
return "form invalid" # render(request, 'auth/signup.html', {'form': form})
else:
email = form.cleaned_data.get('email')
enterprise = form.cleaned_data.get('enterprise')
first_name = form.cleaned_data.get('first_name')
last_name = form.cleaned_data.get('last_name')
password = form.cleaned_data.get('password')
MyUser.objects.create_myuser(email=email, enterprise=enterprise, first_name=first_name, last_name=last_name,
password=password,)
myuser = authenticate(email=email, password=password)
# myuser.backend = 'django.contrib.auth.backends.ModelBackend'
# authenticate(email=email, password=password)
login(request, myuser)
welcome_post = u'{0}from {1} has joined the network.'.format(myuser.first_name, myuser.enterprise)
node = Node(myuser=myuser, post=welcome_post)
node.save()
return redirect('/')
else:
return render(request, 'accounts/signup.html', {'form': SignupForm()})
Also, the user is not getting saved into database.
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\sp\ilog_dev\accounts\views.py" in signup
27. login(request, myuser)
File "C:\Python34\lib\site-packages\django\contrib\auth\__init__.py" in login
98. request.session[BACKEND_SESSION_KEY] = user.backend
File "C:\Python34\lib\site-packages\django\utils\functional.py" in inner
225. return func(self._wrapped, *args)
Exception Type: AttributeError at /accounts/signup/
Exception Value: 'AnonymousUser' object has no attribute 'backend'
models.py
class MyUserManager(BaseUserManager):
def create_myuser(self, email, first_name, last_name, enterprise, password=None):
if not email:
raise ValueError('Users must have an email address')
if not first_name:
raise ValueError("must have a first_name")
if enterprise not in Enterprise.objects.all():
raise ValueError("please specify a valid enterprise or register a new one")
myuser = self.model(email=self.normalize_email(email), first_name=first_name,
last_name=last_name, enterprise=enterprise,)
myuser.set_password(password)
myuser.save() # using=self._db
print("user saved")
return myuser
authenticate
fails and returnsNone
, in which caselogin
will fall back torequest.user
which is anAnonymousUser
without abackend
attribute. – knbkMyUser.objects.create_myuser
can you post the code in this method? – knbk