它已经持续了5天了。它一开始工作得很好但是突然它开始给我一些我无法理解的错误,所以我开始从MyCustomUser模型和自定义身份验证后端修改我的代码但是我仍然无法想出这个问题。
我可以登录用户并在注册后登录用户,但是当我打开django shell并测试user.is_authenticated时它返回True并且user.is_anonymous返回False。
请有人帮我确定这里的问题。请django开发人员。
贝娄是我的签名视图:
def sign_up(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
new_user = form.save(commit=False)
#create string of first_name an last_name
full_name = '{0} {1}' .format(new_user.first_name, new_user.last_name)
#Slugify full name
new_user.slug = slugify(full_name)
new_user.save()
email = request.POST.get('email')
raw_password = request.POST.get('password1')
#Authenticate the user
user = authenticate(email=email, password=raw_password)
if user is not None :
login(request, user)
if request.user.is_authenticated:
#Redirect to success url after user has successfully is logged in.
return HttpResponseRedirect(reverse_lazy('jogos:question-list'))
else:
form = SignUpForm()
return render(request, 'jogos/sign_up.html', {'form':form})
from jogos.models import MyCustomUser
from django.contrib.auth import get_user_model
我的CustomBackend,我也插入了我的设置。
class MyCustomBackend(object):
def authenticate(self, request, email=None, password=None, **kwargs):
if email is None:
email = kwargs.get('email')
try:
user = MyCustomUser.objects.get(email=email)
if user.check_password(password):
return user
else:
return None
except MyCustomUser.DoesNotExist:
return None
def get_user(self, user_id):
try:
user = MyCustomUser.objects.get(pk=user_id)
if user.is_active:
return user
except MyCustomUser.DoesNotExist:
return None
我的CustomUser型号:
class MyCustomUser(AbstractBaseUser):
email = models.EmailField(max_length=50, verbose_name='email', unique=True)
first_name = models.CharField( max_length=15,blank=False)
last_name = models.CharField( max_length=15,blank=True)
slug = models.SlugField(null=True, unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def get_full_name(self):
full_name = '{0} {1}'.format(self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@property
def is_superuser(self):
return self.is_superuser
@property
def is_staff(self):
return self.is_staff
def __str__(self):
return self.first_name
另外我的UserManager:
from django.contrib.auth.base_user import BaseUserManager
class UserManager(BaseUserManager):
use_in_migrations = True
def create_user(self, email, password=None):
if not email:
raise ValueError("Users must have an email address")
email = UserManager.normalize_email(email)
user = self.model(email=email)
user.set_password(password)
user.is_active = True
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(email, password=password)
user.is_active = True
user.is_superuser = True
user.is_admin = True
user.save(using=self._db)
return user
我无法弄清楚这里出了什么问题,而且所有这些代码都运行顺畅 这一切都只是在我继续发展我的代码库时才开始给我带来麻烦
答案 0 :(得分:3)
你的逻辑是错误的。在您登录用户之前,request.user
根据定义是未经身份验证的用户。所以request.user.is_authenticated
永远都是假的。
您不需要或想要检查那里的财产。你不是真的需要检查用户是不是没有,因为你刚刚创建它,所以你知道它存在。只需直接登录用户。
(注意,我不明白为什么你创建了一个自定义身份验证后端。它没有做任何与标准后端不同的事情。你不需要它。)
答案 1 :(得分:0)
使用Authorization标头发送令牌后,令牌将在以下分发函数中获得:
def dispatch(self, request, *args, **kwargs):
self.args = args
self.kwargs = kwargs
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
self.initial(request, *args, **kwargs)
# Get the appropriate handler method
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
response = handler(request, *args, **kwargs)
except Exception as exc:
response = self.handle_exception(exc)
self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response
因此,您使用的是django_role_permission的HasRoleMixin,此mixin的dispatch方法将隐藏视图的派发。我认为解决方案是重新定义角色权限的组合