Django 实现WEB登陆(第一版)

简介:
http://blog.51cto.com/guoshiwei/1899959



本文转自 gswljy 51CTO博客,原文链接:http://blog.51cto.com/guoshiwei/1899959

实现环境:

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

[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

相关文章
|
23天前
|
设计模式 前端开发 数据库
Python Web开发:Django框架下的全栈开发实战
【10月更文挑战第27天】本文介绍了Django框架在Python Web开发中的应用,涵盖了Django与Flask等框架的比较、项目结构、模型、视图、模板和URL配置等内容,并展示了实际代码示例,帮助读者快速掌握Django全栈开发的核心技术。
125 45
|
5天前
|
开发框架 搜索推荐 数据可视化
Django框架适合开发哪种类型的Web应用程序?
Django 框架凭借其强大的功能、稳定性和可扩展性,几乎可以适应各种类型的 Web 应用程序开发需求。无论是简单的网站还是复杂的企业级系统,Django 都能提供可靠的支持,帮助开发者快速构建高质量的应用。同时,其活跃的社区和丰富的资源也为开发者在项目实施过程中提供了有力的保障。
|
19天前
|
API 数据库 开发者
深度剖析Django/Flask:解锁Web开发新姿势,让创意无限延伸!
在Web开发领域,Django与Flask如同两颗璀璨的星辰,各具特色。Django提供全栈解决方案,适合快速开发复杂应用;Flask则轻量灵活,适合小型项目和API开发。本文通过问答形式,深入解析两大框架的使用方法和选择策略,助你解锁Web开发新技能。
34 2
|
1月前
|
机器学习/深度学习 数据处理 数据库
基于Django的深度学习视频分类Web系统
基于Django的深度学习视频分类Web系统
55 4
基于Django的深度学习视频分类Web系统
|
24天前
|
安全 数据库 开发者
Python Web开发:Django框架下的全栈开发实战
【10月更文挑战第26天】本文详细介绍了如何在Django框架下进行全栈开发,包括环境安装与配置、创建项目和应用、定义模型类、运行数据库迁移、创建视图和URL映射、编写模板以及启动开发服务器等步骤,并通过示例代码展示了具体实现过程。
35 2
|
27天前
|
安全 数据库 C++
Python Web框架比较:Django vs Flask vs Pyramid
Python Web框架比较:Django vs Flask vs Pyramid
37 1
|
1月前
|
安全 数据库 C++
Python Web框架比较:Django vs Flask vs Pyramid
Python Web框架比较:Django vs Flask vs Pyramid
30 4
|
1月前
|
安全 数据库 C++
Python Web框架比较:Django vs Flask vs Pyramid
【10月更文挑战第10天】本文比较了Python中三个最受欢迎的Web框架:Django、Flask和Pyramid。Django以功能全面、文档完善著称,适合快速开发;Flask轻量灵活,易于上手;Pyramid介于两者之间,兼顾灵活性和安全性。选择框架时需考虑项目需求和个人偏好。
36 1
|
1月前
|
机器学习/深度学习 监控 数据挖掘
基于Django和百度飞桨模型的情感识别Web系统
基于Django和百度飞桨模型的情感识别Web系统
38 5
|
1月前
|
安全 数据库 C++
Python Web框架比较:Django vs Flask vs Pyramid
【10月更文挑战第6天】本文比较了Python中三个最受欢迎的Web框架:Django、Flask和Pyramid。Django功能全面,适合快速开发;Flask灵活轻量,易于上手;Pyramid介于两者之间,兼顾灵活性和可扩展性。文章分析了各框架的优缺点,帮助开发者根据项目需求和个人偏好做出合适的选择。
36 4
下一篇
无影云桌面