Django2.0.6 学习笔记-----------------登录界面与后台逻辑

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/soulwyb/article/details/86445305

通过导入一下模块即可实现静态页面的展现(根目录前不添加'/':

from django.views.generic import TemplateView

path('', TemplateView.as_view(template_name= "index.html"), name=  "index")
path('login/', TemplateView.as_view(template_name= "login.html"), name=  "login")

静态文件目录的配置:

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

在</form>前一行添加{% csrf_token %} 来防止403错误

request中的POST中是一个queryset的对象。我们可以把它当成一个字典来用(GET其实也是)。

使用authenticate来验证用户名密码是否存在。使用login来将登录成功的信息(应该是user对象)写入到request中。通过render返回给浏览器

from django.contrib.auth import authenticate, login

def user_login(request):
    if request.method == "POST":
        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:
            login(request, user)
            return render(request, "index.html")
        else:
            return render(request, "login.html", {})

在前端页面中通过以下if-else语句对是否登录的页面进行判断

{% if request.user.is_authenticated %}
    <div>
        显示登陆后的信息,比如个人信息。头像之类的
    </div>
{% else %}
    <div>
        显示未登录的HTML样式
    </div>
{% endif %}

猜你喜欢

转载自blog.csdn.net/soulwyb/article/details/86445305