• Anaconda+django写出第一个web app(八)


    今天来实现网站的登入和登出功能。

    首先我们需要在urls.py中添加路径,注意此处的路径和在导航栏中设置的文字路径保持一致:

    from django.urls import path
    from . import views
    
    app_name = 'main' #此处为了urls的命名空间
    
    urlpatterns = [
        path('', views.homepage, name='homepage'),
        path('register/', views.register, name='register'),
        path('logout/', views.logout_request, name='logout_request'),
        path('login/', views.login_request, name='login_request'),
    ]

    在view.py中添加登出和登入的函数,登出的函数非常简单,只需要使用logout函数登出并给出登出成功的信息,然后导向主页即可。登入函数需要使用新的表单AuthenticationForm,并判断用户是否存在,如果存在则登入并进入主页,如果不存在则给出错误信息:

    from django.shortcuts import render, redirect
    from django.http import HttpResponse
    from .models import Tutorial
    from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
    from django.contrib.auth import login, logout, authenticate
    from django.contrib import messages
    # Create your views here.
    def homepage(request):
        return render(request=request, 
                template_name='main/home.html',
                context={'tutorials':Tutorial.objects.all})
    
    def register(request):
        if request.method == 'POST':
            form = UserCreationForm(request.POST)
            if form.is_valid():
                user = form.save()
                username = form.cleaned_data.get('username')
                messages.success(request, f"New account created: {username}")
                login(request, user)
                return redirect('main:homepage')
            else:
                for msg in form.error_messages:
                    messages.error(request, f"{msg}:{form.error_messages[msg]}")
    
                return render(request=request,
                    template_name='main/register.html',
                    context={'form':form})
    
        form = UserCreationForm
        return render(request=request,
                template_name='main/register.html',
                context={'form':form})
    
    def logout_request(request):
        logout(request)
        messages.info(request, f"Logged out successfully!")
        return redirect('main:homepage')
    
    def login_request(request):
        if request.method == 'POST':
            form = AuthenticationForm(request=request, data=request.POST)
            if form.is_valid():
                username = form.cleaned_data.get('username')
                password = form.cleaned_data.get('password')
                user = authenticate(username=username, password=password)
                if user is not None:
                    login(request, user)
                    messages.info(request, f"You are now logged in as {username}")
                    return redirect('main:homepage')
                else:
                    messages.error(request, f"Invalid username or passowrd.")
            else:
                messages.error(request, f"Invalid username or passowrd.")
    
    
        form = AuthenticationForm
        return render(request=request,
                template_name='main/login.html',
                context={'form':form})

    登入登出及信息显示如下,第二幅图显示“You are now logged in as xiaohonghong”,这个就是toast的效果:

     

    与之前的几节不同,我在这里修改了导航栏的颜色,并添加了container效果,修改方法如下,通过style设置背景颜色,将container加入到div的class中:

      <nav style="background-color: #008E72">
        <div class="nav-wrapper container">

    现在使用的注册表单是materialize默认的,我们希望注册的时候可以加入邮箱这个选项,这样忘记密码的时候就可以通过邮箱来找回密码,如何自定义注册表单呢?方法如下,在main文件夹下新建forms.py:

    from django.contrib.auth.forms import UserCreationForm
    from django import forms
    from django.contrib.auth.models import User
    
    class NewUserForm(UserCreationForm):
        email = forms.EmailField(required=True)
    
        class Meta:
            model = User
            fields = ("username", "email", "password1", "password2")
    
        def save(self, commit=True):
            user = super(NewUserForm, self).save(commit=False)
            user.email = self.cleaned_data.get('email')
            if commit:
                user.save()
            return user

    然后将views.py中的UserCreationForm修改为NewUserForm即可,在浏览器点击Register得到如下界面,可以看到email这一样出现了:

    参考链接:

    [1] https://pythonprogramming.net/user-login-logout-django-tutorial/?completed=/messages-django-tutorial/

  • 相关阅读:
    初识JSP知识
    Session每次访问都回新建对象问题的处理
    C++ 重载中括号
    C++ 重载输出符号
    C++ 单目运算 and 双目运算符重载complex
    C++运算符重载范例
    c++ 运算符重载之成员函数重载
    c++ 友元函数
    c++ static 类
    c++ const 类
  • 原文地址:https://www.cnblogs.com/yunxiaofei/p/10424834.html
Copyright © 2020-2023  润新知