zoukankan      html  css  js  c++  java
  • django学习笔记(1)

    Django 特点

    强大的数据库功能
         用python的类继承,几行代码就可以拥有一个丰富,动态的数据库操作接口(API),如果需要你也能执行SQL语句

    自带的强大的后台功能
         几行简单的代码就让你的网站拥有一个强大的后台,轻松管理你的内容!

    优雅的网址
         用正则匹配网址,传递到对应函数,随意定义,如你所想!

    模板系统
         强大,易扩展的模板系统,设计简易,代码,样式分开设计,更容易管理。

    缓存系统
         与memcached或其它的缓存系统联用,更出色的表现,更快的加载速度。

    国际化
         完全支持多语言应用,允许你定义翻译的字符,轻松翻译成不同国家的语言。





    Django 全貌一览

    urls.py
         网址入口,关联到对应的views.py中的一个函数(或者generic类),访问网址就对应一个函数。

    views.py
         处理用户发出的请求,从urls.py中对应过来, 通过渲染templates中的网页可以将显示内容,比如登陆后的用户名,用户请求的数据,输出到网页。

    models.py
         与数据库操作相关,存入或读取数据时用到这个,当然用不到数据库的时候 你可以不使用。

    forms.py
         表单,用户在浏览器上输入数据提交,对数据的验证工作以及输入框的生成等工作,当然你也可以不使用。

    templates 文件夹
         views.py 中的函数渲染templates中的Html模板,得到动态内容的网页,当然可以用缓存来提高速度。

    admin.py
         后台,可以用很少量的代码就拥有一个强大的后台。

    settings.py
         Django 的设置,配置文件,比如 DEBUG 的开关,静态文件的位置等。




    Django 基本命令

    新建 项目
         $ django-admin startproject mysite

    新建 app
         $ python manage.py startapp blog
         一般一个项目有多个app, 当然通用的app也可以在多个项目中使用。

    同步数据库
         $ python manage.py migrate

    使用开发服务器
         $ python manage.py runserver [port]

    清空数据库
         $ python manage.py flush

    创建超级管理员
         $ python manage.py createsuperuser

    导出数据
         $ python manage.py dumpdata blog > blog.json

    导入数据
         $ python manage.py loaddata blog.json

    项目环境终端
         $ python manage.py shell

    数据库命令行
         $ python manage.py dbshell

    查看更多命令
         $ python manage.py



    创建一个简单例子的流程

    环境:windows7 + python3.4 + django1.8

    ====> Creating a project
         $ django-admin startproject mysite
         $ cd mysite


    ====> Database setup
         $ edit mysitesettings.py

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

         $ python manage.py migrate


    ====> The development server (http://127.0.0.1:800)
         $ python manage.py runserver


    ====> Creating models
         $ python manage.py startapp polls
         $ edit pollsmodels.py

    from django.db import models
    
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
    
    class Choice(models.Model):
        question = models.ForeignKey(Question)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)



    ====> Activating models
         $ edit mysitesettings.py

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

         $ python manage.py makemigrations polls
         $ python manage.py sqlmigrate polls 0001
         $ python manage.py migrate

    Remember the three-step guide to making model changes:
        Change your models (in models.py).
        Run python manage.py makemigrations to create migrations for those changes
        Run python manage.py migrate to apply those changes to the database.】


    ====> Playing with the API
         $ python manage.py shell

    >>> from polls.models import Question, Choice
    >>>
    >>> Question.objects.all() []
    >>>
    >>> from django.utils import timezone
    >>>
    >>> q = Question(question_text="What's new?", pub_date=timezone.now()) >>> q.save()
    >>>
    >>> q.id 1 >>> q.question_text "What's new?" >>> q.pub_date datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
    >>>
    >>> q.question_text = "What's up?" >>> q.save()
    >>>
    >>> Question.objects.all() [<Question: Question object>]

    ====> Change models.py
         edit pollsmodels.py

    import datetime
    
    from django.db import models
    from django.utils import timezone
    
    class Question(models.Model):
        # ...
        def __str__(self):              # __unicode__ on Python 2
            return self.question_text
    
        def was_published_recently(self):
            return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    
    
    class Choice(models.Model):
        # ...
        def __str__(self):              # __unicode__ on Python 2
            return self.choice_text



    ====> Play the API again

         python manage.py shell

    >>> from polls.models import Question, Choice
    >>>
    >>> Question.objects.all() [<Question: What's up?>]
    >>> >>> Question.objects.filter(id=1) [<Question: What's up?>]
    >>>
    >>> Question.objects.filter(question_text__startswith='What') [<Question: What's up?>] >>>
    >>> from django.utils import timezone
    >>>
    >>> current_year = timezone.now().year >>> Question.objects.get(pub_date__year=current_year) <Question: What's up?> >>>
    >>> Question.objects.get(id=2) Traceback (most recent call last): ... DoesNotExist: Question matching query does not exist. >>> Question.objects.get(pk=1) <Question: What's up?> >>>
    >>> q = Question.objects.get(pk=1) >>> q.was_published_recently() True >>> q = Question.objects.get(pk=1) >>>
    >>>
    >>> q.choice_set.all() [] >>> q.choice_set.create(choice_text='Not much', votes=0) <Choice: Not much>
    >>> >>> q.choice_set.create(choice_text='The sky', votes=0) <Choice: The sky>
    >>>
    >>> >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0) >>> c.question <Question: What's up?> >>>
    >>> q.choice_set.all() [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] >>> q.choice_set.count() 3
    >>> >>> Choice.objects.filter(question__pub_date__year=current_year) [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
    >>>
    >>> c = q.choice_set.filter(choice_text__startswith='Just hacking') >>> c.delete()
  • 相关阅读:
    关于App_Offline.htm的应用实例(及CIM_DataFile的用法)注意Windows下
    Office2007多个文档打开时,开启多个窗口(独立进程)
    Asp.Net环境下web Pages,web Forms 及MVC的优越及缺点
    批量生成表Create SQL 示例 Generate SQL Create Scripts for existing tables with Query
    Different between datetime and timestamp, and its setting
    SqlConnection ,SqlTransaction,SqlCommand的常用法
    ASP.NET下从Server端下载文件到Client端C#
    C#中Remote文件复制简例子
    DOS BAT用法简例子
    改善SQL Procedure性能的几点方法
  • 原文地址:https://www.cnblogs.com/hhh5460/p/4458879.html
Copyright © 2011-2022 走看看