Tag: Django
Create a project and an application
# Django-admin.pystartproject MyAdmin
# Cd MyAdmin
#python manage.py startapp online
650) This. width = 650; "src =" http://s5.51cto.com/wyfs02/M01/8A/91/wKioL1g0N8_Cl7wJAAAD_U1DDxE384.png-wh_500x0-wm_3-wmp_4-s_3854117127.png "Title =" 1.png" alt = "wKioL1g0N8_Cl7wJAAAD_U1DDxE384.png-wh_50"/>
Open the MyAdmin/settings. py file and add the application to it:
650) This. width = 650; "src =" http://s4.51cto.com/wyfs02/M02/8A/94/wKiom1g0N-Gy3p8RAAAPFuiXCCo464.png-wh_500x0-wm_3-wmp_4-s_3707033232.png "Title =" 2.png" alt = "wKiom1g0N-Gy3p8RAAAPFuiXCCo464.png-wh_50"/>
Design Database
Open the MyAdmin/online/models. py file and add the following content:
From Django. DB import models
# Create your models here.
Class user (models. Model ):
Username = models. charfield (max_length = 50)
Password = models. charfield (max_length = 50)
Def _ Unicode _ (Self ):
Return self. Username
Perform the following Database Synchronization:
# Python manage. py syncdb
Operations toperform:
Apply all migrations: Admin, contenttypes, auth, sessions
Runningmigrations:
Applying contenttypes.0001 _ initial... OK
Applying auth.0001 _ initial... OK
Applying admin.0001 _ initial... OK
Applying sessions.0001 _ initial... OK
You haveinstalled Django's auth system, and don't have any superusers defined.
Wocould you liketo create one now? (Yes/No): Yes
Username (leaveblank to use 'root'): Root
Email Address: [email protected]
Password:
Password (again ):
Superusercreated successfully.
[[Email protected] # Python manage. py makemigrations
Migrations for 'online ':
0001_initial.py:
-Create model user
[[Email protected] # Python manage. py migrate
Operations toperform:
Apply all migrations: Admin, contenttypes, sessions, auth, online
Runningmigrations:
Applying online.0001 _ initial... OK
ConfigurationURL
Open MyAdmin/URLs. py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(‘‘,
# Examples:
# url(r‘^$‘, ‘mysite5.views.home‘, name=‘home‘),
url(r‘^admin/‘, include(admin.site.urls)),
url(r‘^online/‘, include(‘online.urls‘)),
)
Create the URLs. py file in the mysite5/online/directory:
from django.conf.urls import patterns, url
from online import views
urlpatterns = patterns(‘‘,
url(r‘^$‘, views.login, name=‘login‘),
url(r‘^login/$‘,views.login,name = ‘login‘),
url(r‘^regist/$‘,views.regist,name = ‘regist‘),
url(r‘^index/$‘,views.index,name = ‘index‘),
url(r‘^logout/$‘,views.logout,name = ‘logout‘),
)
Create View
Open the MyAdmin/online/views. py file:
#coding=utf-8
from django.shortcuts import render,render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
from django import forms
from models import User
# Form
class UserForm(forms.Form):
Username = forms. charfield (Label = 'username', max_length = 100)
Password = forms. charfield (Label = 'Password', widget = forms. passwordinput ())
# Registration
def regist(req):
if req.method == ‘POST‘:
uf = UserForm(req.POST)
if uf.is_valid():
# Obtain form data
username = uf.cleaned_data[‘username‘]
password = uf.cleaned_data[‘password‘]
# Add to database
User.objects.create(username= username,password=password)
return HttpResponse(‘regist success!!‘)
else:
uf = UserForm()
return render_to_response(‘regist.html‘,{‘uf‘:uf}, context_instance=RequestContext(req))
# Login
def login(req):
if req.method == ‘POST‘:
uf = UserForm(req.POST)
if uf.is_valid():
# Getting the form User Password
username = uf.cleaned_data[‘username‘]
password = uf.cleaned_data[‘password‘]
# Compare the obtained form data with the database
user = User.objects.filter(username__exact = username,password__exact = password)
if user:
# Jump to index if the comparison is successful
response = HttpResponseRedirect(‘/online/index/‘)
# Write the username into the browser cookie. The expiration time is 3600.
response.set_cookie(‘username‘,username,3600)
return response
else:
# Comparison failed, still in Login
return HttpResponseRedirect(‘/online/login/‘)
else:
uf = UserForm()
return render_to_response(‘login.html‘,{‘uf‘:uf},context_instance=RequestContext(req))
# Login successful
def index(req):
username = req.COOKIES.get(‘username‘,‘‘)
return render_to_response(‘index.html‘ ,{‘username‘:username})
# Exit
def logout(req):
response = HttpResponse(‘logout !!‘)
# Clear the cookie and save Username
response.delete_cookie(‘username‘)
return response
All registration and login logic are implemented here, And Cookie creation, reading, and deletion operations are used in the middle.
Create Template
First, create the templates directory under the mysite5/online/directory, and then create the regist.html file under the mysite5/online/templates/directory:
<? Xmlversion = "1.0" encoding = "UTF-8"?>
<! Doctypehtml public "-// W3C // dtd xhtml 1.0 strict // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<Htmlxmlns = "http://www.w3.org/1999/xhtml" XML: lang = "en" lang = "en">
<Head>
<Metahttp-equiv = "Content-Type" content = "text/html; charsets = UTF-8"/>
<Title> Registration </title>
</Head>
<Body>
<H1> registration page:
<Form method = 'post' enctype = "multipart/form-Data">
{% Csrf_token %}
{UF. as_p }}
<Input type = "Submit" value = "OK"/>
</Form>
<Br>
<Ahref = "http: // 127.0.0.1: 8000/online/login/"> login </a>
</Body>
</Html>
Create a login.html file under MyAdmin/online/templates/directory:
<? Xmlversion = "1.0" encoding = "UTF-8"?>
<! Doctypehtml public "-// W3C // dtd xhtml 1.0 strict // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<Htmlxmlns = "http://www.w3.org/1999/xhtml" XML: lang = "en" lang = "en">
<Head>
<Metahttp-equiv = "Content-Type" content = "text/html; charsets = UTF-8"/>
<Title> login </title>
</Head>
<Body>
<H1> logon page:
<Form method = 'post' enctype = "multipart/form-Data">
{% Csrf_token %}
{UF. as_p }}
<Input type = "Submit" value = "OK"/>
</Form>
<Br>
<Ahref = "http: // 127.0.0.1: 8000/online/regist/"> register </a>
</Body>
</Html>
Create the index.html file under MyAdmin/online/templates/directory:
<? Xmlversion = "1.0" encoding = "UTF-8"?>
<! Doctypehtml public "-// W3C // dtd xhtml 1.0 strict // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<Htmlxmlns = "http://www.w3.org/1999/xhtml" XML: lang = "en" lang = "en">
<Head>
<Metahttp-equiv = "Content-Type" content = "text/html; charsets = UTF-8"/>
<Title> </title>
</Head>
<Body>
<H1> welcome {username }}! </H1>
<Br>
<Ahref = "http: // 127.0.0.1: 8000/online/logout/"> exit </a>
</Body>
</Html>
Usage
Register
650) This. width = 650; "src =" http://s4.51cto.com/wyfs02/M00/8A/94/wKiom1g0OGGhdUdHAAA2pbCrnhE308.png-wh_500x0-wm_3-wmp_4-s_614378496.png "Title =" 3.png" alt = "wkiom11_ogghdudhaaa2pbcrnhe308.png-wh_50"/>
Login
650) This. width = 650; "src =" http://s1.51cto.com/wyfs02/M01/8A/94/wKiom1g0OHODUIZYAABTlcAi6Lc092.png-wh_500x0-wm_3-wmp_4-s_1463399318.png "Title =" 4.png" alt = "wkiom1?ohoduizyaabtlcai6lc092.png-wh_50"/>
This article is from the "Do not forget your mind" blog. For more information, contact the author!
Registration, login, and use of cookies in django1.7