• django简单demo


    django简单demo
    环境:
    CentOS 7.2
    python2.7.12
    django1.8



    一.创建vitualenv并安装django
    virtualenv dj1.8
    source dj1.8/bin/activate
    pip install django==1.8

    二.创建project
    mkdir project
    django-admin startproject blog project/

    三.配置
    project/blog/settings.py
    提示:服务正常run之后,配置文件修改无需重启服务即可生效
    i.授权监听地址
    ALLOWED_HOSTS = ['127.0.0.1','localhost','192.168.43.144','192.168.8.254']
    否则会有的通有ip能访问有的不能
    ii.数据库配置
    1.建库与授权
    默认的sqlite3可以直接启动,这里使用mysql,mysql安装配置请参看MariaDB-10.1.x二进制包安装
    create database django character set utf8;
    grant all on django.* to 'djadmin'@'%' identified by 'djpassword' with grant option;
    flush privileges;

    2.安装mysql驱动
    pip install MySQL-python
    3.db连接配置
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'django',
            'USER': os.environ['DJANGO_USER'],
            'PASSWORD': os.environ['DJANGO_PASSWORD'],
            'HOST': '192.168.8.254',
            'PORT': '3306',
        
    }

    提示:认证信息可以直接明文写入,也可以通过options来调用外部配置。本文从变量中获取
    4.初始化db
    python manage.py migrate
    5.创建superuser
    python manage.py createsuperuser                                                                                       

    其它配置
    LANGUAGE_CODE = 'zh-hans'        #zh-CN                              
    TIME_ZONE = 'Asia/Shanghai'

    四.启动
    python manage.py runserver 0.0.0.0:8000

    192.168.43.144:8000/admin/
    django简单demo
    后台美化示例
    https://github.com/django-admin-bootstrap/django-admin-bootstrap
    django简单demo

    django简单demo



    五.创建app
    django-admin startapp project/blog/app #或python project/blog/manage.py startapp app

    i.导入app
    project/blog/settings.py
    INSTALLED_APPS = (   
        'django.contrib.admin',   
        'django.contrib.auth',   
        'django.contrib.contenttypes',   
        'django.contrib.sessions',   
        'django.contrib.messages',   
        'django.contrib.staticfiles',   
        'app',   
     

    ii.后台自定义表单
    1.project/blog/app/models.py
    from django.db import models        
            
    # Create your models here.       
                                                                                                                                              
    class Article(models.Model):                                                                                                                         
        title = models.CharField(max_length=250)                                                                                                         
        category = models.CharField(max_length=50, blank=True)                                                                                           
        date_time = models.DateTimeField(auto_now_add=True)                                                                                              
        content = models.TextField(blank=True, null=True)                                                                                                
                                                                                                                                                         
        def __unicode__(self):                                                                                                                           
            return self.title                                                                                                                            
                                                                                                                                                         
        class Meta(object):                                                                                                                              
            verbose_name = 'blog'                                                                                                                        
            verbose_name_plural = 'blog'                                                                                                                 
            ordering = ['-date_time'] 

    1.project/blog/app/admin.py
    from django.contrib import admin   
    from models import Article   
       
    admin.site.register(Article)

    注意:每次修改models,都要执行makemigrations动作,这样才能正常变更数据库
    python manage.py makemigrations app
    python manage.py migrate
    django简单demo

    django简单demo


    六.hello world

    ii.返回内容
    project/app/views.py
    from django.shortcuts import render   
    from django.http import HttpResponse
    import time
    # Create your views here.   
       
    def hello(request):
        return HttpResponse('%s %s' % ('hello world!',time.strftime('%Y-%m-%d')))

    2.路由
    project/blog/urls.py
    from django.conf.urls import include, url   
    from django.contrib import admin   
    from app import views   
       
    urlpatterns = [   
        # Examples:   
        # url(r'^$', 'myblog.views.home', name='home'),   
        # url(r'^blog/', include('blog.urls')),   
       
        url(r'^admin/', include(admin.site.urls)), 
        url(r'^hello/$', views.hello, name='hello world'),
    ]


    七.模板渲染
    i.创建app静态文件目录
    mkdir -p project/app/{static,templates}
    ii.copy静态文件到app目录
    1.下载demo模板
    git clone http://github.com/liujun1990/templates.git
    unzip templates/blog_demo.zip
    解压出html目录,编码问题请cat README
    2.静态文件copy到约定目录
    iconv -f GB2312 -t UTF8 html/index.html -o foo
    mv foo app/templates/index.html
    mv html/* app/static
    iii.返回内容
    project/app/views.py
    from django.shortcuts import render  
    from django.http import HttpResponse
    import time

    # Create your views here.   
      
    def hello(request):
        return HttpResponse('%s %s' % ('hello world!',time.strftime('%Y-%m-%d')))

    def index(request):
        return render(request, 'index.html')
    iv.路由
    from django.conf.urls import include, url   
    from django.contrib import admin   
    from app import views   
       
    urlpatterns = [   
        # Examples:   
        # url(r'^$', 'myblog.views.home', name='home'),   
        # url(r'^blog/', include('blog.urls')),   
       
        url(r'^admin/', include(admin.site.urls)),  
        url(r'^hello/$', views.hello, name='hello world'),
        url(r'^$', views.index, name='homepage'),   
    ]

    v.引用静态文件
    project/app/templates/index.html
    django简单demo


    效果
    django简单demo

  • 相关阅读:
    python移动文件,将一个文件夹里面的文件移动到另一个文件夹
    python中的os.path.join, os.path.splitext, os.path.split, split()函数用法
    python遍历目录下的所有目录和文件, python解析json文件, python-opencv截取子图
    Python对文件进行批量重命名
    python遍历目录下的所有目录和文件,并用opencv从mp4文件中抽帧得到图片
    python中的os.walk()方法学习
    ubuntu16.04 安装caffe时出现 .build_release/tools/caffe: error while loading shared libraries: libcudart.so.10.0: cannot open shared object file: No such file or directory
    caffe编译过程中的错误: nvcc fatal : Unsupported gpu architecture 'compute_20'
    Java字符串为""和null的区别
    一次docker中的nginx进程响应慢问题定位记录
  • 原文地址:https://www.cnblogs.com/lixuebin/p/10813987.html
Copyright © 2020-2023  润新知