Django开发笔记六

Django开发笔记一

Django开发笔记二

Django开发笔记三

Django开发笔记四

Django开发笔记五

Django开发笔记六

 

1、登录功能完善

登录成功应该是重定向到首页,而不是转发,当前用户信息保存到session:

class LoginView(View):
    def get(self, request):
        return render(request, "login.html", {})

    def post(self, request):
        user_name = request.POST.get("username", "")
        pass_word = request.POST.get("password", "")
        user = authenticate(username=user_name, password=pass_word)

        if user is not None:
            dj_login(request, user)
            request.session['currentUser'] = json.dumps(user, default=UserProfile.user2json)
            return HttpResponseRedirect("/")
        else:
            return render(request, "login.html", {'msg': None})

 用户需要提供序列化方法:

class UserProfile(AbstractUser):
    nickname = models.CharField(max_length=50, verbose_name=u"昵称")
    birthday = models.DateField(max_length=50, null=True, blank=True, verbose_name=u"生日")
    gender = models.CharField(choices=(("male", u"男"), ("female", u"女"), ("secret", u"保密")), default=u"secret",
                              max_length=10)
    address = models.CharField(max_length=100, default=u"")
    mobile = models.CharField(max_length=11, null=True, blank=True)
    image = models.ImageField(upload_to="user/%y/%m", default=u"images/default/user_default.png",
                              max_length=100)
    add_time = models.DateTimeField(default=datetime.now)

    class Meta:
        verbose_name = u"用户"
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    def __unicode__(self):
        return self.username

    def user2json(self):
        return {'username': self.username, 'nickname': self.nickname, 'id': self.id, 'image': self.image.url}

 

xadmin在后台添加用户也需要加密:

xadmin添加用户应该是可以配置密码加密类型的,但是我没找到,所以修改源码:

xadmin/views/edit.py

    @filter_hook
    def isave_forms(self):
        self.new_obj = self.form_obj.save(commit=False)
        # 后台添加用户默认密码是123456
        if self.request.get_full_path() == '/admin/users/userprofile/add/':
            setattr(self.new_obj, 'password', make_password('123456'))

 之所以setattr,是应为self.new_obj['password']=make_password('123456'))直接赋值报错('UserProfile' object does not support item assignment).

posted @ 2017-10-17 11:45  懒企鹅  阅读(314)  评论(0编辑  收藏  举报