1、环境说明
系统:CentOS release 6.5
[[email protected] gouwu]# pip install django==1.6.5
[[email protected] gouwu]# wget http://effbot.org/media/downloads/Imaging-1.1.5.tar.gz 安装PIL
2、启动Django
[[email protected] gouwu]# django-admin.py startproject aaa (创建项目工程)
[[email protected] gouwu]# cd aaa/
[[email protected] aaa]# python manage.py startapp app (创建app)
[[email protected] aaa]# ls
aaa app manage.py
[[email protected] aaa]# vim aaa/settings.py (添加app,设置语言时区)
INSTALLED_APPS = ( ‘app‘, )
LANGUAGE_CODE = ‘zh-cn‘
TIME_ZONE = ‘Asia/Chongqing‘
3、查看效果
[[email protected] aaa]# python manage.py runserver 192.168.1.179:8002 (启动)
python manage.py runserver 0.0.0.0:8000 (启动方式,不然只能使用127.0.0.1:8000访问)
http://192.168.1.179:8001 (web端查看,出现“It worked!”为正常)
4、首页显示
修改配置文件:url.py和视图文件view.py
[[email protected] aaa]# cat aaa/urls.py 配置url,增加一行
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(‘‘,
# Examples:
# url(r‘^$‘, ‘aaa.views.home‘, name=‘home‘),
# url(r‘^blog/‘, include(‘blog.urls‘)),
url(r‘^$‘, ‘app.views.index‘),
url(r‘^admin/‘, include(admin.site.urls)),
)
[[email protected] aaa]# cat app/views.py 配置视图,导入模块,增加函数
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
#print "some is visting my site"
return HttpResponse("Welcome to website")
启动:[[email protected] aaa]# python manage.py runserver 0.0.0.0:8001
输入:http://192.168.1.179:8001/,显示“Welcome to Website”即为正常
5、app显示
[[email protected] aa]# python manage.py syncdb (初始化数据库,默认sqlite)
通过配置账号密码管理admin,此时生成用户表、认证等表,可以通过以下链接登录admin管理平台。
http://192.168.1.179:8001/admin/,进入只有用户和组两个大类
下列操作
[[email protected] aaa]# cat app/models.py (设置显示参数、参数显示方式)
from django.db import models
class Shangpin(models.Model):
name = models.CharField(‘name‘,max_length=40)
num = models.IntegerField(‘num‘,max_length=12)
price = models.FloatField(‘price‘,default=20)
def __unicode__(self):
return "%s-%d -- %f"% (self.name,self.num,self.price)
[[email protected] aaa]# cat app/admin.py 注册admin,导入模块,增加注册信息
from django.contrib import admin
from models import Shangpin
admin.site.register(Shangpin)
此时需要重新生成数据库,因为增加了新字段(也可以直接进入数据库后台新增)
页面登录自行添加product参数,查看如下显示。http://192.168.1.179:8001/admin/
6、增加参数
继续增加参数,产品类型。
编辑models.py和admin.py两个配置文件,这里就不一一展示。
class Demo(models.Model):
name = models.CharField(‘name‘,max_length=30)
num = models.IntegerField(‘num‘,default=100)
def __unicode__(self):
return "%s: %d" % (self.name,self.num)
---------------
两张表没有联系,需要将他们联系相关
-----将没有关联的数据表关联,通过外键将两者联系起来(*)
class Product(models.Model):
name = models.CharField(‘product name‘,max_length=30)
price = models.FloatField(‘price‘,default=10)
ptype = models.ForeignKey(‘Ptype‘)
需要重新更新数据库,否则报错。
[[email protected] eshop]# rm -fr db.sqlite3 (对sqlite数据库不熟悉,删除重建)
[[email protected] eshop]# python manage.py syncdb