我正在尝试创建用户登录。但是当我登录时,我收到错误消息:
TypeError: get_by_natural_key() takes exactly 3 arguments (2 given)
There was a similar question asked before, but it never got resolved
我不知道它要求的第三个论点是什么。我只是从Django自己的用户管理器中复制粘贴 get_by_natural_key ,并将其放入我自己的自定义模型中。
这是我的用户模型:
class CustomUserManager(models.Manager):
def get_absolute_url(self):
return "/u/%s/" % urlquote(self.username)
def get_username(self):
'Returns the username'
return self.username
def get_full_name(self):
"""
#Returns the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
" Returns the short name for the user."
return self.first_name
def _create_user(self, username, email, password, **extra_fields):
"""
Creates and saves a User with the given username, email and password.
"""
if not username:
raise ValueError('The given username must be set')
email = self.normalize_email(email)
user = self.model(username=username, email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, email=None, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(username, email, password, **extra_fields)
def create_superuser(self, username, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', 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(username, email, password, **extra_fields)
@classmethod
def normalize_email(cls, email):
"""
Normalize the address by lowercasing the domain part of the email
address.
"""
email = email or ''
try:
email_name, domain_part = email.strip().rsplit('@', 1)
except ValueError:
pass
else:
email = '@'.join([email_name, domain_part.lower()])
return email
def get_by_natural_key(self, username, password):
return self.get(username=username, password=password)
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField('email address', unique=True, db_index=True)
username = models.CharField('username', max_length=50, unique=True, db_index=True)
first_name = models.CharField(max_length=50, blank=False)
last_name = models.CharField(max_length=50, blank=False)
joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __unicode__(self):
return self.username
class Meta:
unique_together = (('username', 'password'),)
views.py
def register_user(request):
if request.method == 'POST':
form = RegistrationForm(request.POST) # create form object
if form.is_valid():
form.save()
return HttpResponseRedirect('/all')
args = {}
args.update(csrf(request))
args['form'] = RegistrationForm()
print args
return render(request, 'register.html', args)
def login(request):
"""
User Log in View
"""
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
CustomUser = authenticate(username=request.POST['username'], password=request.POST['password'])
if CustomUser is not None:
if CustomUser.is_active:
django_login(request, CustomUser)
return redirect('all_posts.html')
else:
form = AuthenticationForm()
return render_to_response('login.html', {
'authenticationform': form,
}, context_instance=RequestContext(request))
答案 0 :(得分:4)
Django自己的get_by_natural_key
方法仅需要username
个参数 - 您的方法需要username
以及password
(不确定从哪里复制)。来自documentation:
get_by_natural_key(username)
使用USERNAME_FIELD指定的字段内容检索用户实例。
删除你的password
参数,它应该可以工作(无论如何通过密码获取都没有任何意义):
def get_by_natural_key(self, username):
return self.get(username=username)
更好的是,为什么不将BaseUserManager
子类化,而不是重新实现其逻辑?您目前正在继承models.Manager
。