Django implements the Website login function

Source: Internet
Author: User

The Django version is as follows:

[Email protected] testoms]# python-c "Import Django;print Django. VERSION "(1, 3, U ' final ', 0) [[email protected] testoms]#

Django By default there is a login interface, that is, when you start Project, in the browser to enter "Extranet IP address/admin" will see the default login interface Django,

650) this.width=650; "src=" Https://s3.51cto.com/wyfs02/M02/91/E7/wKioL1j5Z3LxJneeAABpIXtmo_A575.png "title=" 1.png "alt=" Wkiol1j5z3lxjneeaabpixtmo_a575.png "/>


But we still want to be able to make an interface where our internal users can log on to the platform, and this article is about how to achieve this.


In http://chenx1242.blog.51cto.com/10430133/1914949 I have built a project called Testoms, which has two apps, App1 and App2, respectively. and App1 and APP2 have been added to the Installed_apps node in Testoms's settings.py, as follows:

Installed_apps = [' django.contrib.admin ', ' Django.contrib.auth ', ' django.contrib.contenttypes ', ' django.contr Ib.sessions ', ' django.contrib.messages ', ' django.contrib.staticfiles ', ' App1 ', ' app2 ',]


Then comment out the CSRF in the middleware:

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 ' , ' Debug_toolbar.middleware.DebugToolbarMiddleware ',]


At this point the contents of the testoms/testoms/url.py are initialized, and this is the case:

From django.conf.urls import urlfrom django.contrib import adminurlpatterns = [url (r ' ^admin/', admin.site.urls),]


Now we set up a small data table in the App1, can be used to store the password of the account, came to Testoms/app1 inside,#vim models.py, edited into the following content:

From __future__ import unicode_literalsfrom django.db import modelsfrom django.contrib import Adminclass User (models. Model): Username = models. Charfield (max_length=50) password = models. Charfield (MAX_LENGTH=50) class useradmin (admin. Modeladmin): List_display = (' username ', ' password ') admin.site.register (user,useradmin)


See we set up a class called user, there are two fields are username and password, the maximum number of bytes is 50, here is easier to set up, if you want to do a bit more sophisticated, you can add a mailbox or mobile phone number or something.


Return to the Testoms directory,#python manage.py migrate will see that the database has been synchronized, and then #python manage.py createsuperuser to create a superuser, This will allow you to log in to the Django backend. After landing the background will see App1 's menu bar more than one of the users, that is, the above we set the "class" Name:

650) this.width=650; "src=" Https://s3.51cto.com/wyfs02/M00/91/E9/wKiom1j5bimgoni8AAAKTSoHpaA712.png "title=" 1.png "alt=" Wkiom1j5bimgoni8aaaktsohpaa712.png "/>


Then click Add, just add a user, such as user called "Lidakang", the password is 123123:

650) this.width=650; "src=" Https://s5.51cto.com/wyfs02/M01/91/EA/wKiom1j5bveA7-l8AAAfluwMAwQ310.png "title=" 1.png "alt=" Wkiom1j5bvea7-l8aaafluwmawq310.png "/>


When you click Save, you'll see the effect:

650) this.width=650; "src=" Https://s2.51cto.com/wyfs02/M02/91/E9/wKioL1j5cHzC_YiwAAAzfv0PYUE058.png "title=" 1.png "alt=" Wkiol1j5chzc_yiwaaazfv0pyue058.png "/>


Can see we have set Lidakang can login to our Django, that is, we have a small database called Lidakang data, then the User information table has been generated, the following is to do is the user login function.


In the views.py of Testoms/app1, change to this content:

#coding =utf-8from django.shortcuts import render,render_to_responsefrom django.http  import httpresponseredirectfrom app1.models import user         #因为在app1下的操作, so here to write app1from django import forms# define form model Class userform (forms. Form):     username = forms. Charfield (label= ' username: ', max_length=100)     password = forms. Charfield (label= ' Password: ',     widget=forms. Passwordinput ()) #登录def  login (Request):           if  request.method ==  ' POST ':        uf =  UserForm (Request. POST)                 if  Uf.is_valid ():                      #获取表单User Password             username = uf.cleaned_ data[' username ']            password =  uf.cleaned_data[' Password ']                          #获取的表单数据与数据库进行比较              user = user.objects.filter (username__exact =  username,password__exact = password)                          if user:                                  return render_to_response (' Success.html ', {' username ': UsernaMe})                          else:                                  return httpresponseredirect ('/login/')           else:         uf = userform ()           return render_to_response (' login.html ', {' UF ': uf})



This code means that the "account" and "password" are obtained at the time of the post, and if the input data is consistent with the field of the database User data table, jump to the Success.html interface (and the Username field is set to " Username '), instead, continue to stay on the login.html page.


Now we are going to set success.html interface and Login.html interface, in Testoms/app1/templates,#vim login.html, the content is as follows:

<! Doctype html>


After you save the exit, create an interface called success.html:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >< HTML xmlns= "http://www.w3.org/1999/xhtml" xml:lang= "en" lang= "en" >


Return to App1 This level directory, manually create a file called urls.py, fill in the following content:

From django.conf.urls import urlfrom app1 import viewsurlpatterns = [url (r ' ^$ ', views.login, name= ' login '),]


After saving, return to the Testoms/testoms layer directory and modify the contents of the urls.py:

From django.conf.urls import url,includefrom django.contrib import Adminadmin.autodiscover () from App1 import views as app 1_viewsfrom app2 Import views as App2_viewsurlpatterns = [url (r ' ^admin/', Admin.site.urls), #url (R ' ^$ ', app1_views. Hello,name= ' hello '), url (r ' ^bye/$ ', app2_views.bye,name= ' bye '), url (r ' ^login/', include (' App1.urls ')), # used here just now in a urls.py file created under PP1]


Restart Django and enter "Extranet IP address/login" in the browser's address bar to see our results:

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M00/91/F3/wKiom1j5p9XgfJtrAAEuYm7ze40153.png "title=" 1.png "alt=" Wkiom1j5p9xgfjtraaeuym7ze40153.png "/>


Enter the Lidakang we just created and the corresponding password 123123, click OK, you will see the successful interface:

650) this.width=650; "src=" Https://s2.51cto.com/wyfs02/M02/91/EA/wKioL1j5diHwbkusAAA-dSGu8Sw214.png "title=" 1.png "alt=" Wkiol1j5dihwbkusaaa-dsgu8sw214.png "/>

This article is from "Life is waiting for Gordo" blog, please make sure to keep this source http://chenx1242.blog.51cto.com/10430133/1917985

Django implements the Website login function

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.