Using Django, MySQL, HTML, JS, Ajax to simulate the development of blog system (4)

Next, let's do the login function

We first create a login.html in templates to display the login page

  • <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script type="text/javascript" src="/static/js/jquery-3.3.1.js"></script>
        <script>
            $(function (){
                $("input[name='username']").blur(function () {
                   //alert("")
                    uname=$("input [name='username']").val()
                    CSRF=$("input[name='csrfmiddlewaretoken']").val()
                    $.ajax({
                        url:'/BlogUser/getUser',
                        data:{'uname':uname,'csrfmiddlewaretoken':CSRF},
                        type:'POST',
    
    
                    });
                });
            });
        </script>
    </head>
    <body>
    <h1>Welcome to login</h1>
    <form action="/BlogUser/login" method="post">
        {% csrf_token %}
        用户名:<input type="text" name="username" value="{{ username }}">
        <br>
        密  码:<input type="password" name="pwd">
        <label style="color: red">{{ error1 }}</label><br>
    
        <input type="submit" value="登录">
        </form>
    </body>
    </html>

Then create a login function login() in views.py

  • def login(request):
        if request.method=='GET':
            return render(request,'login.html')
        else:
           username=request.POST.get('username')
           pwd=request.POST.get('pwd')
           blogUserSet=BlogUser.objects.filter(username=username,password=pwd)
           if len(blogUserSet)==1:
               return redirect(reverse('user:welcome',args=[blogUserSet.first().id]))
           else:
               return render(request,'login.html',{'error1':'password error'})

Import welcome in blog\urls.py and configure the path in BlogUser.vews.py

The login is successful and the user information is put into the session

  • After we log in successfully, we need to display the user information on the page, and when jumping to other pages, the user is still logged in and the browser can recognize it, which requires session scope
  1. installed_apps

    2. Middleware (help us enable session)

    3. Setting storage form (stored in the setting database)

Session can only store json, that is, dictionary-type data
. The design principle of django session:
      a. If the user requests for the first time (depending on whether the client ie saves the sessionId cookie),
                create a session model 
                and generate a key sessionId with a random character The string (uuid makes the id never repeat)
                is saved to the location specified by your session_engine
                and saved to the cookie, in the client's browser
       b. If the second request or more, the client ie will automatically submit the cookie to django, django Use the SessionMiddleware middleware you configured to activate the session, use the sessionID in the cookie to read the session model at the specified location of session_engine, and set
            it to the session attribute of the request.

         session itself is a dict field

         When the session stores data, the data must support serialization of json)

We first need to create a table in the database for the app's session

  • Use the shell command migrate sessions

    1. Start manage.py again

        2. Enter the migrate sessions command

 At this time, we will find that a session table is created in the data to store the session creation time and expiration time (the default time is two weeks)

Then we modify the code in views.py to let the user log in and save it in the session so that any function can get information in the session later

After the login is successful, we close the browser, open the browser again, and enter http://127.0.0.1:8000/welcome in the address bar to find that the content remains unchanged

To be continued. . .

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325828273&siteId=291194637