1. 程式人生 > >Django開發筆記六

Django開發筆記六

功能 username return ural time url brush .post 方法

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}

Django開發筆記六