前言
对于web开来说,用户登陆、注册、文件上传等是最基础的功能,针对不同的web框架,相关的文章非常多,但搜索之后发现大多都不具有完整性,对于想学习web开发的新手来说就没办法一步一步的操作练习;对于web应用来说,包括数据库的创建,前端页面的开发,以及中间逻辑层的处理三部分。
本系列以可操作性为主,介绍如何通过django web框架来实现一些简单的功能。每一章都具有完整性和独立性。使用新手在动手做的过程中体会web开发的过程,过程中细节请参考相关文档。
本操作的环境:
===================
deepin linux 2013(基于ubuntu)
python 2.7
Django 1.6.2
===================
创建项目与应用
#创建项目
fnngj@fnngj-H24X:~/djpy$ django-admin.py startproject mysite2
fnngj@fnngj-H24X:~/djpy$ cd mysite2
#在项目下创建一个disk应用
fnngj@fnngj-H24X:~/djpy/mysite2$ python manage.py startapp disk
目录结构如下:
打开mysite2/mysite2/settings.py文件,将disk应用添加进去:
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'disk',
)
设计Model(数据库)
打开mysite2/disk/models.py文件,添加如下内容
from django.db importmodels#Create your models here.
classUser(models.Model):
username= models.CharField(max_length = 30)
headImg= models.FileField(upload_to = './upload/')def __unicode__(self):return self.username
创建两个字段,username 用户存放用户名,headImg 用户存放上传文件的路径。
下面进行数据库的同步
fnngj@fnngj-H24X:~/djpy/mysite2$ 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 disk_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 'fnngj'): 用户名(默认当前系统用户名)
Email address: fnngj@126.com 邮箱地址
Password: 密码
Password (again): 确认密码
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
最后生成的 disk_user 表就我是我们models.py 中所创建的类。Django 提供了他们之间的对应关系。
创建视图
1、打开mysite2/disk/views.py 文件
from django.shortcuts importrender,render_to_response#Create your views here.
defregister(request):return render_to_response('register.html',{})
2、创建注册页面
先在mysite2/disk/目录下创建templates目录,接着在mysite2/disk/templates/目录下创建register.html 文件: