Every bady, have a look, have a look!
Finally, we have reached the most exciting link. From today on, we will learn django login and registration. Are you very excited (dog) before starting today's notes, we still need to know some basic concepts.
- The first one: django is how to render web pages
- Second: what is CBV and what is FBV
- Third: what is csrf
Fourth: what is a cookie and what is a session
But
The above four questions are a separate note, each of which can be said for a long time. I won't repeat them here today.
Today's task is to write a simple login code, and then analyze the code inside. This time it is still a draft, and the code inside may be modified later. Everything is subject to the latest code
Step 1 url.py
The old rule is to attach the code first
"""moou URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path import xadmin from apps.users import views as Uview urlpatterns = [ path('admin/', xadmin.site.urls), path('',Uview.index,name='index'), path('login/',Uview.LoginView.as_view(),name='login') ] from django.conf.urls.static import static from moou import settings urlpatterns += static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)
path('',Uview.index,name='index'), path('login/',Uview.LoginView.as_view(),name='login')
These two pieces of code point to the index function and the login function respectively
Look carefully. The first function called later is the module name plus the corresponding function "Uview.index"
The second one is also in front, but the LoginView here is a class, followed by an as_vies()
It also points to a function, but why are the methods called different.
why......?
The difference here is one of the several knowledge we need to know at the beginning
What is CBV and what is FBV
In short, one is to use classes to write function methods, and the other is to use methods to write function methods. Specifically, a blog will be written in detail later. I want to leave a suspense here
Step 2 view.py
Here, I created the logic in view.py under the users app. In fact, I can write it anywhere. However, this logic involving user login and registration is more in line with the overall specification under the users app. These are digressions
The gossip is over. It's time for a big play
# views.py from django.shortcuts import render from django.views import View from django.contrib.auth import authenticate, login # django comes with login from django.http import HttpResponseRedirect from django.urls import reverse # Create your views here. def index(request): return render(request, 'index.html') class LoginView(View): def get(self, request, *args, **kwargs): return render(request, 'login.html') def post(self, request, *args, **kwargs): user_name = request.POST.get('username') password=request.POST.get('password') user = authenticate(username = user_name,password=password) if user is not None: '''Query user''' login(request,user) # Log in return HttpResponseRedirect(reverse('index')) else: return render(request,'login.html',{'msg':'Wrong user name or password'})
Here are two codes, one is the use method, and the other is the class.
First of all, the index method mainly manages the initialization of the page, which is to return to the home page of the web page. There is nothing to say.
Let's focus on the second LoginView class. There are two methods in total, a get and a post. Let's ignore the get and post methods first.
The function of the post method is to log in the user. The user logs in using the from form at the front end
user_name = request.POST.get('username') password=request.POST.get('password')
Get the user name and password entered
user = authenticate(username = user_name,password=password)
In this section, django automatically judges whether the entered user name and password are in the database. We don't have to check the database manually. djagno has automatically helped us check whether it is good or not
if user is not None: '''Query user''' login(request,user) # Log in return HttpResponseRedirect(reverse('index')) else: return render(request,'login.html',{'msg':'Wrong user name or password'})
Here is the last step. Judge whether the user exists according to the above. If so, log in. If not, return to the HTML page and return the error message.
Here you may have a question. Why do you use render and HttpResponseRedirect when returning to the page?
In fact, render can also be used here, but there will be a problem that although he returns the web page, the web address of his browser is still / login /, which is a little flawed.
If HttpResponseRedirect is used, it will not. It is usually used with reverse. In reverse, we define the method name after url.py * *, and it will automatically jump to the corresponding url.
Step 4: previous hmtl
First of all, the web pages written in the previous paragraph are all written by the course teachers, such as some js and css styles. I will directly apply the teacher's HTML following the tutorial. At the beginning, it is some cumbersome work to replace some external styles in the HTML web page.
In my previous blog, I mentioned that in django, we defined static, which is specially used to store external styles. The normal code to import external styles is
<link rel="stylesheet" type="text/css" href="../css/style.css">
In django, it needs to be changed to
<link rel="stylesheet" type="text/css" href="/static/css/style.css">
Preceded by / static
After understanding this, we will directly call the shortcut key ctrl+R of pycharm replacement to replace it. This step is too cumbersome, so I don't have a screenshot demonstration.
However, please note that there is a media folder here. It should be a folder at the same level as static, which stores files uploaded by users. However, it will be changed later when it is put into static at the beginning. Don't care too much here.
Because there is too much code, I only copied the login part
<form class="tab-form" action="{% url 'login' %}" method="post" autocomplete="off" id="form1"> <div class="form-group marb20 "> <input name="username" id="account_l" type="text" placeholder="cell-phone number/mailbox" /> </div> <div class="form-group marb8 "> <input name="password" id="password_l" type="password" placeholder="Please enter your password" /> </div> <div class="error btns login-form-tips" id="jsLoginTips"></div> <div class="auto-box marb38"> <a class="fr" href="forgetpwd.html">Forgot your password?</a> </div> <input class="btn btn-green" id="jsLoginBtn" type="submit" value="Log in now > " /> </form>
This login part has not been modified too much, but I add a {% csrf_token%} at the bottom of the form. Here is what CSRF is in my first four questions. Here we'll dig another pit first (which pit is it now)
Anyway, now just remember to add {% csrf_token%} or set it in setting.py when making a post request
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
Medium
django.middleware.csrf.CsrfViewMiddleware
Comment it out.
The following are the main modifications made in index.html
<div class="top"> <div class="wp"> <div class="fl"><p>Service telephone:<b>33333333</b></p></div> <!--Jump after login--> {% if request.user.is_authenticated %} <div class="personal"> <dl class="user fr"> <dd>bobby<img class="down fr" src="/static/images/top_down.png"/></dd> <dt><img width="20" height="20" src="/static/media/image/2016/12/default_big_14.png"/></dt> </dl> <div class="userdetail"> <dl> <dt><img width="80" height="80" src="/static/media/image/2016/12/default_big_14.png"/></dt> <dd> <h2>django</h2> <p>bobby</p> </dd> </dl> <div class="btn"> <a class="personcenter fl" href="usercenter-info.html">Enter the personal Center</a> <a class="fr" href="/logout/">sign out</a> </div> </div> </div> {% else %} <a style="color:white" class="fr registerbtn" href="register.html">register</a> <a style="color:white" class="fr loginbtn" href="{% url 'login' %}">Sign in</a> {% endif %} </div> </div>
Two knowledge points are mainly used here. One is request.user.is_authenticated
This means to judge whether the current website is logged in. Why does the previous paragraph know that the user is logged in??
Please look this way
'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ],
There is such a first key value pair in TEMPLATES in setting.py
context_processors stores the login status of django users. Once the user logs in successfully and the session is saved to the computer, the request can now exist in all web pages and be called.
What is session? I'm digging a pit (how many pits are there, hehe)
{% if . . . %} {% else %} {% endif %}
Is this familiar? This is if judgment. Why is it in the previous paragraph?
By the way, this is an if judgment. This is the front rendering statement of django. There are many front rendering statements of django. I will write an article to introduce them later. (got! Dug another pit)