django初探

参考博客
django官方文档

django的安装与配置
#在线安装
easy_install django
#离线安装
python setup.py install
#安装好后
django_admin.py
#启动核心控制文件
manager.py 
#整个环境配置文件
settings.py 
#路由转发文件
urls.py

这里写图片描述

查看django-admin目录
[root@localhost bin]# which django-admin
/usr/bin/django-admin
You have new mail in /var/spool/mail/root
查看django-admin命令
[root@localhost bin]# django-admin --help
Usage: django-admin subcommand [options] [args]

Options:
  -v VERBOSITY, --verbosity=VERBOSITY
                        Verbosity level; 0=minimal output, 1=normal output,
                        2=verbose output, 3=very verbose output
  --settings=SETTINGS   The Python path to a settings module, e.g.
                        "myproject.settings.main". If this isn't provided, the
                        DJANGO_SETTINGS_MODULE environment variable will be
                        used.
  --pythonpath=PYTHONPATH
                        A directory to add to the Python path, e.g.
                        "/home/djangoprojects/myproject".
  --traceback           Raise on exception
  --no-color            Don't colorize the command output.
  --version             show program's version number and exit
  -h, --help            show this help message and exit

Type 'django-admin help <subcommand>' for help on a specific subcommand.

Available subcommands:

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    runfcgi
    runserver
    shell
    sql
    sqlall
    sqlclear
    sqlcustom
    sqldropindexes
    sqlflush
    sqlindexes
    sqlinitialdata
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    syncdb
    test
    testserver
    validate
创建django项目
[root@localhost data]# django-admin startproject eshop
查看项目文件
[root@localhost data]# cd eshop/
You have new mail in /var/spool/mail/root
[root@localhost eshop]# ls
eshop  manage.py
[root@localhost eshop]# ls eshop/
__init__.py  settings.py  urls.py  wsgi.py
启动django
[root@localhost eshop]# python manage.py  runserver
访问django
http://192.168.174.131:8000/

如果不想自动刷新页面
加参数

[root@localhost eshop]# python manage.py runserver 192.168.0.145:8000 --noreload

还可以指定访问

[root@localhost eshop]# python manage.py runserver 192.168.0.145:8000
测试访问
[root@localhost ~]# curl http://192.168.0.145:8000
查看服务起动
[root@localhost ~]# netstat -tpln
centos7关闭防火墙
[root@localhost ~]# systemctl stop firewalld.service
增加应用
[root@localhost eshop]# python manage.py  startapp order
[root@localhost eshop]# ls
db.sqlite3  eshop  manage.py  order
[root@localhost eshop]# ls order/
admin.py  __init__.py  migrations  models.py  tests.py  views.py

这里写图片描述

wingIDE
new project->add directory -> save project as ->save project as 
set as  main dug file ->点击debug按钮

修改VIEW

[root@localhost order]# pwd
/data/eshop/order
[root@localhost order]# ls
admin.py  __init__.py  migrations  models.py  tests.py  views.py

修改view

[root@localhost order]# cat views.py 
from django.shortcuts import render
from django.http import HttpResponse
Create your views here.
def index(request):
    return HttpResponse("ok!")
修改urls.py
[root@localhost eshop]# pwd
/data/eshop/eshop
[root@localhost eshop]# cat urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'eshop.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^$','order.views.index'),
    url(r'^admin/', include(admin.site.urls)),
)
增加模块名
[root@localhost eshop]# pwd
/data/eshop/eshop
[root@localhost eshop]# ls
__init__.py  __init__.pyc  settings.py  settings.pyc  urls.py  urls.pyc  wsgi.py  wsgi.pyc
[root@localhost eshop]# cat settings.py
"""
Django settings for eshop project.

For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '070+&6!fm4!ye!mxswu&jm_1i2*lp*0%%khporfl+q7uj=g##h'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'order',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'eshop.urls'

WSGI_APPLICATION = 'eshop.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/

STATIC_URL = '/static/'
定义model
[root@localhost order]# pwd
/data/eshop/order
[root@localhost order]# ls
admin.py   __init__.py   migrations  models.pyc  views.py
admin.pyc  __init__.pyc  models.py   tests.py    views.pyc
[root@localhost order]# cat models.py
from django.db import models

# Create your models here.

class Product(models.Model):

    name = models.CharField('product name',max_length=30)

    price = models.FloatField('price',default=10)

    def __unicode__(self):
       return "%s ----> %f"% (self.name,self.price)

#

[root@localhost eshop]# python manage.py  syncdb
在admin.py注册model
[root@localhost order]# pwd
/data/eshop/order
[root@localhost order]# ls
admin.py   __init__.py   migrations  models.pyc  views.py
admin.pyc  __init__.pyc  models.py   tests.py    views.pyc
[root@localhost order]# cat admin.py
from django.contrib import admin
from models import Product
# Register your models here.
admin.site.register(Product)
访问路径
http://192.168.0.145:8000/admin/
How do I fix this Django error“Exception Type: OperationalError Exception Value: no such table?”
Did you run ./manage.py syncdb to create all your tables?
Do you have django.contrib.contenttypes in your INSTALLED_APPS in settings.py?
As an unlikely third option:

Does your project/app use the Django app "South"? If so, you would also need to run ./manage.py migrate to make sure all tables get created.

参考博客数据库不能产生表报错

增加对象映射关系model
from django.db import models

# Create your models here.
class Product(models.Model):

    name = models.CharField('product name',max_length=30)

    price = models.FloatField('price',default=10)
    ptype = models.ForeignKey('Ptype')

    def __unicode__(self):
       return "%s ----> %f"% (self.name,self.price)
class Ptype(models.Model):
    name = models.CharField('type',max_length=10)
    def __unicode__(self):
        return "%s-->" % self.name
增加admin控制
from django.contrib import admin
from models import Product
# Register your models here.
admin.site.register(Product)
admin.site.register(Ptype)
删除数据库
[root@localhost eshop]# rm -rf db.sqlite3 
查看数据库
[root@localhost eshop]#  ./manage.py migrate
Operations to perform:
  Apply all migrations: admin, contenttypes, order, auth, sessions
Running migrations:
  No migrations to apply.
  Your models have changes that are not yet reflected in a migration, and so won't be applied.
  Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
[root@localhost eshop]# ./manage.py makemigrations
Migrations for 'order':
  0002_auto_20150426_1516.py:
    - Create model Person
    - Remove field Manufacturer from car
    - Delete model Car
    - Delete model Manufacturer
    - Delete model Product
[root@localhost eshop]# sqlite3 db.sqlite3        
SQLite version 3.7.17 2013-05-20 00:56:22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
auth_group                  django_content_type       
auth_group_permissions      django_migrations         
auth_permission             django_session            
auth_user                   order_car                 
auth_user_groups            order_manufacturer        
auth_user_user_permissions  order_product             
django_admin_log          
sqlite> .qiut
Error: unknown command or invalid arguments:  "qiut". Enter ".help" for help
sqlite> .quit  
You have new mail in /var/spool/mail/root
[root@localhost eshop]# ./manage.py syncdb
Operations to perform:
  Apply all migrations: admin, contenttypes, order, auth, sessions
Running migrations:
  Applying order.0002_auto_20150426_1516... OK
[root@localhost eshop]# sqlite3 db.sqlite3 
SQLite version 3.7.17 2013-05-20 00:56:22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
auth_group                  django_admin_log          
auth_group_permissions      django_content_type       
auth_permission             django_migrations         
auth_user                   django_session            
auth_user_groups            order_person              
auth_user_user_permissions
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值