Django 实现WEB登陆

实现环境:

1、System version:rh6.5

2、Python version:2.6.6

3、Django version:1.2.7

创建项目:

1、[[email protected] ~]#django-admin.py startproject mysite

2、[[email protected] mysite]#python manage.py startapp app01

3、[[email protected] mysite]#mkdir templates

4、[[email protected] mysite templates]#tourch login.html && tourch success.html

文件配置:

settings.py

# Django settings for mysite project.

DEBUG = True

TEMPLATE_DEBUG = DEBUG

ADMINS = (

# (‘Your Name‘, ‘[email protected]‘),

)

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 images. 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)

[[email protected] mysite]#python manage.py syncdb     //同步数据库

[email protected]:~/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: [email protected]     邮箱地址

Password:    密码

Password (again):    确认密码

Superuser created successfully.

Installing custom SQL ...

Installing indexes ...

Installed 0 object(s) from 0 fixture(s)

访问admin

登录用户名和密码为我们进行数据库同步时所设置的信息。

[[email protected] 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>

运行服务:

[[email protected] mysite]# python manage.py runserver 0.0.0.0:5000

在地址栏输入:http://localhost:5000/login

时间: 2024-10-09 21:54:27

Django 实现WEB登陆的相关文章

Django 实现WEB登陆(第二版)

实现环境: 1.System version:rh6.5 2.Python version:2.6.6 3.Django version:1.2.7 创建项目: 1.[[email protected] ~]#django-admin.py startproject mysite 2.[[email protected] mysite]#python manage.py startapp app01 3.[[email protected] mysite]#mkdir templates 4.[

django简单用户登陆验证

一.django简单用户登陆验证   前端页面:     <div class="container  col-lg-6  col-lg-offset-4">         <br><br><br><br><br>       <form class="form-signin col-sm-4 col-lg-offset-2" action="{% url 'login' %}

django实现用户登陆访问限制@login_required

我们在网站开发过程中,经常会遇到这样的需求:用户登陆系统才可以访问某些页面 如果用户没有登陆而直接访问就会跳转到登陆界面,而不能访问其他页面. 用户在跳转的登陆界面中完成登陆后,自动访问跳转到之前访问的地址 要实现这样的需求其实很简单: 1.使用django自带的装饰器 @login_required. 2.在相应的view方法的前面添加@login_required 3.并在settings.py中配置LOGIN_URL参数 4.修改login.htlm中的表单action参数 #views.

利用Django构建web应用及其部署

注:很久之前就有了学习Django的想法,最近终于有机会做了一次尝试.由于Django的详细教程很多,我在这里就不再详述了,只是将整个开发流程以及自己在学习Django中的一些思考记录在此. System:CentOS Linux release 7.2.1511 (Core) Django: 1.10 Python: 2.7.5 推荐两个非常好的教程: The Django Book(中文版):我自己一开始是参考这个教程学习的,非常有意思的是这个教程中有大量的评论,几乎每段都有,从10年开始一

[Python] 利用Django进行Web开发系列(一)

1 写在前面 在没有接触互联网这个行业的时候,我就一直很好奇网站是怎么构建的.现在虽然从事互联网相关的工作,但是也一直没有接触过Web开发之类的东西,但是兴趣终归还是要有的,而且是需要自己动手去实践的.Web开发的途径有好多种,比如传统的.Net,还有很火爆的Java.Python作为一种灵活好学的脚本语言,已经越来越受程序员的欢迎和热捧,甚至成为程序员的必备技能.Django是Python的Web开放框架,好多人说学习Python就是在学Django,从这也可以看出Django的强大.博主也是

Django实现网站登陆的功能

django版本如下: [[email protected] testoms]# python -c "import django;print django.VERSION" (1, 10, 3, u'final', 0) [[email protected] testoms]# django默认情况下是有一个登陆界面的,就是当你启动project的时候,在浏览器里输入"外网ip地址/admin"就会看到django默认的登陆界面,如图: 但是我们还是希望可以做出来

[zz]阿里云计算:CentOS+nginx+Django+Postgresql web环境搭建

原文链接: http://www.cnblogs.com/AllStarGIS/p/3788518.html 参考链接: 1. http://www.cnblogs.com/zhouej/archive/2012/03/25/2379646.html 2. http://ec58.com/archives/2836 最近在在万网和阿里云上分别购买了一个域名和一台云服务器,打算用来做点什么.昨天吃完晚饭稍作休息开始对这个新奇的玩意作了些了解并着手配置其运行环境,今早凌晨4点多才弄得7788,为此也

使用 Python 和 Django 搭建 Web 应用

使用 Python 和 Django 搭建 Web 应用 简介 Django 是 Python 开发的 Web 框架.使用 Django 搭建 Web 应用很方便. 写本文时 django 的最新版本为 1.4,但本文不关注新版本的特性,只搭建一个简单的应用. 安装 Django 本文以 CentOS 6.2 为例进行安装: 安装 python # yum install python 本文使用的是 CentOS 6.2 Desktop,默认安装了 python. 查看一下 python 的版本

Nginx+uWSGI+Django部署web服务器

目录 Nginx+uWSGI+Django部署web服务器 环境说明 前言 搭建项目 Django部署 编辑luffy/luffy/settings.py 编辑luffy/app01/views.py 编辑luffy/luffy/urls.py 运行并测试 uWSGI部署 测试运行uWSGI 使用uWSGI运行django项目 uWSGi热加载Djangoa项目 部署nginx nginx配置uwsgi和django django部署static文件 重新加载nginx进行测试 测试nginx