Django中的登录

来源:互联网 发布:淘宝二手beats耳机 编辑:程序博客网 时间:2024/05/16 18:55

render(request, template_name, context=None, content_type=None, status=None, using=None)

此方法的作用---结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 HttpResponse 对象。

request: 是一个固定参数, 没什么好讲的。

template_name: templates 中定义的文件, 要注意路径名. 比如'templates\polls\index.html', 参数就要写‘polls\index.html’

context: 要传入文件中用于渲染呈现的数据, 默认是字典格式

content_type: 生成的文档要使用的MIME 类型。默认为DEFAULT_CONTENT_TYPE 设置的值。

status: http的响应代码,默认是200.

using: 用于加载模板使用的模板引擎的名称。

比如

def post(self, request):    login_form = LoginForm(request.POST)    # 验证 POST 的每个参数是否合法    if login_form.is_valid():        user_name = request.POST.get('username', '')        password = request.POST.get('password', '')        # 使用 authenticate() 方法进行验证        user = authenticate(username=user_name, password=password) #利用authenticate验证一个用户如果合法的话返回user对象失败的话返回None        if user is not None:            if user.is_active:                # 使用 login() 方法进行登录接受一个 HttpRequest 对象和一个 User 对象保存参数                login(request, user)  #利用login                 return HttpResponseRedirect(reverse("index"))            else:                return render(request, 'login.html', {'msg': '用户未激活'})        else:            return render(request, 'login.html', {'msg': '用户名或者密码错误!'})返回一个render在登录界面里面 如果auth返回的是空就显示msg,msg需要在html中定义{% msg %}    else:        return render(request, 'login.html', {"login_form": login_form})

在登录后判断用户是否登录 在html中定义{% request.user.is_authenticated %} 定义这些是django为了让你在python中少写逻辑代码


原创粉丝点击