实现环境:
1、System version:rh6.5
2、Python version:2.6.6
3、Django version:1.2.7
创建项目:
1、[root@localhost ~]#django-admin.py startproject mysite
2、[root@localhost mysite]#python manage.py startapp app01
3、[root@localhost mysite]#mkdir templates
4、[root@localhost mysite templates]#tourch login.html && tourch success.html
文件配置:
settings.py
# Django settings for mysite project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3' , # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'DATEBASE_NAME', # Or path to database file if using sqlite3.
'USER': 'DATABASE_USER', # Not used with sqlite3.
'PASSWORD': 'DATABASE_PASSWORD', # Not used with sqlite3.
'HOST': 'DATABASE_HOST', # Set to empty string for localhost. Not used with sqlite3.
'PORT': 'DATABASE_OPTIONS', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and p_w_picpaths. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '&4+fv=q&_#o86a$748*%yolle6&^3(s1#5_k0!!a%q5swwq#uw'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
TEMPLATE_DIRS = (
"/root/mysite/templates"
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'app01'
# Uncomment the next line to enable the admin:
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
models.py
from django.db import models
from django.contrib import admin
# Create your models here.
class User(models.Model):
username = models.CharField(max_length=50)
password = models.CharField(max_length=50)
admin.site.register(User)
[root@localhost mysite]#python manage.py syncdb //同步数据库
fnngj@fnngj-H24X:~/djpy/mysite4$ python manage.py syncdb
Creating tables ...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table login_user
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes 输入yes/no
Username (leave blank to use 'root'): 用户名(默认当前系统用户名)
Email address: gswcfl2013@sina.cn 邮箱地址
Password: 密码
Password (again): 确认密码
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
访问admin
登录用户名和密码为我们进行数据库同步时所设置的信息。
[root@localhost mysite]# python manage.py runserver 0.0.0.0:5000
在这里面填写登陆帐号http://localhost:5000/admin
urls.py
from django.conf.urls.defaults import *
from django.shortcuts import render_to_response
from django.shortcuts import HttpResponse
from django.contrib import admin
from app01 import views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^login/',views.login),
#(r'^$',views.index),
)
views.py
#-*-codeing:uft8 -*-
# Create your views here.
from django.shortcuts import render_to_response
from django.shortcuts import HttpResponse
from django.http import HttpResponseRedirect
from app01.models import User
from django import forms
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():
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})
login.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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>登录</title>
</head>
<style type="text/css">
body{color:#efd;background:#453;padding:0 5em;margin:0}
h1{padding:2em 1em;background:#675}
h2{color:#bf8;border-top:1px dotted #fff;margin-top:2em}
p{margin:1em 0}
</style>
<body>
<h1>登录页面:</h1>
<form method = 'post' enctype="multipart/form-data">
`uf`.`as_p`
<input type="submit" value = "ok" />
</form>
</body>
</html>
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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>
<h1>恭喜`username`,登录成功!</h1>
</form>
</body>
</html>
运行服务:
[root@localhost mysite]# python manage.py runserver 0.0.0.0:5000
在地址栏输入:http://localhost:5000/login