我正在使用 django 1.7 python 3.4 我创建了一个从 AbstractBaseUser 派生的自定义 MyUser 类。现在,当我尝试注册用户时,我收到错误“匿名用户”对象没有属性“后端”。视图.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()})
此外,用户没有被保存到数据库中。
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'
模型.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