Django "17th" Ajax implements user login

Source: Internet
Author: User
Tags button type session id

First, need to know the new knowledge point

1, refresh the verification code. Add one to the SRC attribute? No. Add one? Will go back to the request

        #给验证码刷新        $ (". Vialdcode_img"). Click (function () {         mode one: Dom Method #}            $ (this) [0].src+= "?] #}         Way two: jquery's attr Method #}            $ (this). attr ("src", $ (this). attr ("src") + '? ')        })    

2, when the login successfully jump, or register a successful jump

$ (". Register"). Click (function () {            location.href = '/register/'  });

3. Disappear after timeout

SetTimeout (foo, 3000)
function foo () {                $ (". Error"). HTML ("")            }

4, the use of Auth module

Import of modules:

From Django.contrib Import Auth

Several ways to use:

1, Authenticate (): Verify that the user entered the user name and password is the same

Provide user authentication, that is, verify the user name and password is correct, generally need username password two keyword parameters

user = Authenticate (username= ' someone ', password= ' Somepassword ')
2, Login (HttpRequest, user): Login

The function accepts a HttpRequest object, and an authenticated user object

This function uses the Django session framework to attach information such as session ID to an authenticated user.

From Django.contrib.auth import Authenticate, login   def my_view (request):  username = Request. post[' username ']  password = Request. post[' password ']  user = Authenticate (username=username, Password=password)  if User:    login (Request, user )    # Redirect to a success page.    ...  else:    # Return an ' invalid login ' error message.    ... Copy Code
3. Logout (Request) logout user  

The function accepts a HttpRequest object with no return value. When the function is called, the session information for the current request is cleared. Even if the user is not logged in, using this function will not error.

From Django.contrib.auth import logout   def logout_view (request):  logout (Request)  # Redirect to a success Page.
4. The user object's is_authenticated ()

Requirements:

1. Users can access certain pages after they log in

2, if the user does not log in to visit the page directly jump login page

3, the user in the jump login interface to complete the login, automatic access to the previous access to the address

def my_view (Request):  if not request.user.is_authenticated ():    return redirect ('%s?next=%s '% (settings. Login_url, Request.path))

In the background with request.user.is_authenticated () to determine whether the user is logged in, if True can be displayed to the front desk request.user.name

Several methods of user object 2.2, creating users: Create_user
From django.contrib.auth.models Import useruser = User.objects.create_user (username= ", password=", email= ")
2.3, Check_password (passwd): password check

用户需要修改密码的时候 首先要让他输入原来的密码 ,如果给定的字符串通过了密码检查,返回 True

2.4, Change Password: Set_password ()
user = User.objects.get (username= ") User.set_password (password=") user.save

Second, the specific implementation of the login

urls.py

urlpatterns = [url (r '    ^admin/', admin.site.urls),    url (r ' ^login/$ ', views.login),    url (r ' ^index/$ ', views.index),    url (r ' ^get_vaildcode_img/$ ', views.get_vaildcode_img),    url (r ' ^log_out/$ ', views.log_out),    

view.py

DEF login (Request): If request.method== "GET": Return render (Request, "login.html") Else:username = RE Quest. Post.get ("username") Password = Request. Post.get ("password") Vialdcode = Request. Post.get ("Vialdcode") ret = {"Flag": False, "error_msg": None} if vialdcode.upper () = = Request.session.get ("Kee                P_valid_code "). Upper (): User = Auth.authenticate (username=username, Password=password) if User:                #如果验证成功就让登录 Auth.login (request,user) ret["flag"] = True Else: ret["error_msg"] = "username and password Error" else:ret["error_msg"] = "Authenticode error" return HttpResponse (Json.dumps ( RET) def index (request): #验证是不是当前进来的那个用户, if the user is already logged in, you can see the page # If you are not logged in and you do not see the main page, simply return to the login page if not request.user.is_authe    Nticated (): Return redirect ("/login/") Else:return render (Request, "index.html") def log_out (Request): Auth.logout (Request) return redirect ("/login/") def get_vaildcode_img (Request): # Way One: This way the path is written dead, can only be that one picture # import OS # path = Os.path.join (settings.     Base_dir, "Static", "image", "3.jpg") # with open (path, "RB") as f: # data = F.read () # return HttpResponse (data) # Way Two: Each time a different picture is displayed, using the Pillow module, install a pillow module # from PIL import Image # img = image.new (mode= "RGB", size= (120,40), Colo R= "Green") #首先自己创建一个图片, the parameter size= (120,40) represents the long and high # f = open ("Validcode.png", "WB") #然后把图片放在一个指定的位置 # Img.save (F, "PNG") #保  Save Picture # F.close () # with open ("Validcode.png", "RB") as f: # data = F.read () # return HttpResponse (data) # Way three: # Way two is not very good, because each time to create a file to save the picture, we can not let the picture saved to the hard disk, # in memory, the end of automatic purge, then introduced the way three: using Bytesio module # from IO import Bytesi O # from PIL import Image # img = image.new (mode= "RGB", size= (120,40), color= "Blue") # f = Bytesio () #内存文件句柄 # Img.save (F, "PNG") #保存文件 # data = F.getvalue () #打开文件 (equivalent to F.read () in Python) # return HttpResponse (data) # Way four: 1, add brush , which is to write some text on the picture # 2, and font random, background color random from IO import bytesio from PIL import image,imagedraw,imagefont import random #随机创建图片 img =    Image.new (mode= "RGB", size= (120,40), color= (Random.randint (0,255), Random.randint (0,255), Random.randint (0,255))) Draw = Imagedraw.draw (img, "RGB") # Draw interference line for I in range (5): x1 = random.randint (0) y1 = Random.ran Dint (0, max) x2 = random.randint (0, +) y2 = random.randint (0, +) draw.line ((x1, y1, x2, y2), fill= ( Random.randint (0,255), Random.randint (0,255), Random.randint (0,255))) font = Imagefont.truetype ("static/font/ Kumo.ttf ",") #20表示20像素 str_list = [] #吧每次生成的验证码保存起来 # randomly generated five characters for I in range (5): Random_num = str (rand Om.randint (0, 9)) # random number random_lower = Chr (Random.randint (65, 90)) # random lowercase letter Random_upper = Chr (Random.ran Dint (97, 122)) # random capital letters Random_char = Random.choice ([Random_num, Random_lower, Random_upper]) print (random_ Char, "Random_char") Str_list.append (RAndom_char) # (5 + i * 24, 10) represents coordinates, the position of the font Draw.text ((5+i*24,10), Random_char, (Random.randint (0,255), Random.ran   Dint (0,255), Random.randint (0,255)), Font=font) print (str_list, "str_list") F = Bytesio () #内存文件句柄 Img.save (F, "PNG") #img是一个对象 data = F.getvalue () #读取数据并返回至HTML valid_str = "". Join (str_list) print (Valid_str, "Valid_str") reque st.session["Keep_valid_code"] = Valid_str #吧保存到列表的东西存放至session中 return HttpResponse (data)

  

Template

Login.html
<! DOCTYPE html>

  

Index.html
<! DOCTYPE html>

  

Login.css
. container {    margin-top:100px;    margin-left:330px;}. Error {    color:red;}. btn {    width:200px;}. vialdcode_img{    width:200px;    height:40px;}

  

Django "17th" Ajax implements user login

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.