Python之路【第十六篇】:Django【基础篇】

Python的WEB框架有Django、Tornado、Flask 等多种,Django相较与其他WEB框架其优势为:大而全,框架本身集成了ORM、模型绑定、模板引擎、缓存、Session等诸多功能。

基本配置

一、创建django程序

  • 终端命令:django-admin startproject sitename
  • IDE创建Django程序时,本质上都是自动执行上述命令

其他常用命令:

  python manage.py runserver 0.0.0.0
  python manage.py startapp appname
  python manage.py syncdb
  python manage.py makemigrations
  python manage.py migrate

  python manage.py createsuperuser

二、程序目录

三、配置文件

1、数据库

DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME':'dbname',
    'USER': 'root',
    'PASSWORD': 'xxx',
    'HOST': '',
    'PORT': '',
    }
}

  

# 由于Django内部连接MySQL时使用的是MySQLdb模块,而python3中还无此模块,所以需要使用pymysql来代替
  
# 如下设置放置的与project同名的配置的 __init__.py文件中
  
import pymysql
pymysql.install_as_MySQLdb() 

  

2、模版

TEMPLATE_DIRS = (
        os.path.join(BASE_DIR,'templates'),
    )

3、静态文件

STATICFILES_DIRS = (
        os.path.join(BASE_DIR,'static'),
    )

  

路由系统

1、每个路由规则对应一个view中的函数

url(r'^index/(\d*)', views.index),
url(r'^manage/(?P<name>\w*)/(?P<id>\d*)', views.manage),
url(r'^manage/(?P<name>\w*)', views.manage,{'id':333}),

2、根据app对路由规则进行一次分类

url(r'^web/',include('web.urls')),

  

django中的路由系统和其他语言的框架有所不同,在django中每一个请求的url都要有一条路由映射,这样才能将请求交给对一个的view中的函数去处理。其他大部分的Web框架则是对一类的url请求做一条路由映射,从而是路由系统变得简洁。

通过反射机制,为django开发一套动态的路由系统Demo: 点击下载

 

模板

1、模版的执行

模版的创建过程,对于模版,其实就是读取模版(其中嵌套着模版标签),然后将 Model 中获取的数据插入到模版中,最后将信息返回给用户。

 

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

  

from django import template
t = template.Template('My name is {{ name }}.')
c = template.Context({'name': 'Adrian'})
print t.render(c)

 

import datetime
from django import template
import DjangoDemo.settings
 
now = datetime.datetime.now()
fp = open(settings.BASE_DIR+'/templates/Home/Index.html')
t = template.Template(fp.read())
fp.close()
html = t.render(template.Context({'current_date': now}))
return HttpResponse(html

  

from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
import datetime
 
def current_datetime(request):
    now = datetime.datetime.now()
    t = get_template('current_datetime.html')
    html = t.render(Context({'current_date': now}))
    return HttpResponse(html)

  

return render_to_response('Account/Login.html',data,context_instance=RequestContext(request))

  

2、模版语言

 模板中也有自己的语言,该语言可以实现数据展示

  • {{ item }}
  • {% for item in item_list %}  <a>{{ item }}</a>  {% endfor %}
      forloop.counter
      forloop.first
      forloop.last 
  • {% if ordered_warranty %}  {% else %} {% endif %}
  • 母板:{% block title %}{% endblock %}
    子板:{% extends "base.html" %}
       {% block title %}{% endblock %}
  • 帮助方法:
    {{ item.event_start|date:"Y-m-d H:i:s"}}
    {{ bio|truncatewords:"30" }}
    {{ my_list|first|upper }}
    {{ name|lower }}

3、自定义simple_tag

a、在app中创建templatetags模块

b、创建任意 .py 文件,如:xx.py

#!/usr/bin/env python
#coding:utf-8
from django import template
from django.utils.safestring import mark_safe
from django.template.base import resolve_variable, Node, TemplateSyntaxError
  
register = template.Library()
  
@register.simple_tag
def my_simple_time(v1,v2,v3):
    return  v1 + v2 + v3
  
@register.simple_tag
def my_input(id,arg):
    result = "<input type='text' id='%s' class='%s' />" %(id,arg,)
    return mark_safe(result)

装饰器注册继续

@register.simple_tag
def get_comment_handler(info_comment):
    return 123

  

c、在使用自定义simple_tag的html文件中导入之前创建的 xx.py 文件名

{% load xx %}

 

  

d、使用simple_tag

{% my_simple_time 1 2 3%}
{% my_input 'id_username' 'hide'%}

  

e、在settings中配置当前app,不然django无法找到自定义的simple_tag  

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

如果有继承模板需要放在继承模板下面

{% extends "_lay_mu_out/_layout.html" %}
{% load get_comment %}

  

 

  

simpletag 与  filter  区别代码示例

 

 

                {% if forloop.counter|detail3:"4,0" %}  {# 第一个参数要放在方法前面接管道 第二个参数用冒号,只接受2个参数,第二个参数可以做成字符串,用逗号分割#}


{#                {% detail1 item forloop.counter 4 0 %} # 这里用simpletag#}

  

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django import template
from django.utils.safestring import mark_safe
# from django.template.base import resolve_variable, Node, TemplateSyntaxError

register = template.Library()

@register.simple_tag
def my_simple_time(v1,v2,v3):
    return  v1 + v2 + v3

@register.simple_tag
def detail1(item,counter,allcount,remainder):
    temp = """
        <div style="width: 245px;">
            <img style="width: 245px;height: 200px;" src="/%s">
            <p>%s</p>
            <p>%s</p>
            <p >%s...</p>
        </div>
        """
    if counter%allcount == remainder:
        if len(item['letter_of_thanks']) >30:
            item['letter_of_thanks'] = item['letter_of_thanks'][0:30]
        temp = temp %(item['student__pic'],
                      item['student__name'],
                      item['student__salary'],
                      item['letter_of_thanks'])
        return mark_safe(temp)
    else:
        return ""



@register.filter
def detail3(value,arg):# filter 只接受两个参数,我们前端可以用逗号分割开多个参数作为一个字符串

    """
    查看余数是否等于   remainder arg = "1,2"
    :param value:
    :param arg:
    :return:
    """

    allacount ,remainder = arg.split(",")
    allacount = int(allacount)

    remainder = int(remainder)

    if value%allacount == remainder:
        return True
    return False


@register.simple_tag
def action1(current_url,item,id_class):
    id_class = int(id_class)
    url_part = current_url.split("-")
    url_part_id = str(item['id'])
    if id_class != 3:
        url_part[id_class] = url_part_id
    else:
        url_part[id_class] = url_part_id + ".html"
    new_cureent_url = ("-").join(url_part)

    not_html = current_url.split("-")[id_class]
    yes_html = current_url.split("-")[id_class].split(".")[0]
    if not_html == url_part_id or yes_html == url_part_id:
        html_cur = "<a href=%s class='active'>%s</a>" %(new_cureent_url,item["name"])
    else:
        html_cur = "<a href=%s>%s</a>" %(new_cureent_url,item["name"])


    return mark_safe(html_cur)

@register.simple_tag
def action_all(current_url,id_class):

    id_class = int(id_class)
    url_part = current_url.split("-")
    print(url_part,id_class)
    if id_class !=3:
        url_part[id_class]= str(0)
    else:
        url_part[id_class] = str(0)+ ".html"

    new_current_url = ("-").join(url_part)

    not_html = current_url.split("-")[id_class]
    yes_html = current_url.split("-")[id_class].split(".")[0]
    if not_html == str(0) or yes_html == str(0):
        html_cur = "<a href=%s class='active'>%s</a>" %(new_current_url,"全部:")

    else:
        html_cur = "<a href=%s>%s</a>" %(new_current_url,"全部:")

    return mark_safe(html_cur)
{% load xx %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <div>

    </div>
    <style>
        .clearfix:after{
            content: '.';
            visibility: hidden;
            height: 0;
            clear: both;
            display: block;
        }
    </style>

    <div style="margin: 0 auto;width: 980px;" class="clearfix">
        <div style="width: 245px;float: left">
            {% for item in detail_list %}

                {% detail1 item forloop.counter 4 1 %}

            {% endfor %}
        </div>
        <div style="width: 245px;float: left">
            {% for item in detail_list %}
                {% detail1 item forloop.counter 4 2 %}
            {% endfor %}
        </div>
        <div style="width: 245px;float: left">
            {% for item in detail_list %}
                {% detail1 item forloop.counter 4 3 %}
            {% endfor %}
        </div>
        <div style="width: 245px;float: left">

            {% for item in detail_list %}

{#                {% detail1 item forloop.counter 4 0 %} # 这里用simpletag#}
{#                下面用filter 单独用 {{ forloop.counter|detail3:"4,0" }} #}
                {% if forloop.counter|detail3:"4,0" %}  {# 第一个参数要放在方法前面接管道 第二个参数用冒号,只接受2个参数,第二个参数可以做成字符串,用逗号分割#}
                    <div style="width: 245px;">
                        <img style="width: 245px;height: 200px;" src="/{{ item.student__pic }}">
                        <p>{{ item.student__name }}</p>
                        <p>{{ item.student__salary }}</p>
                        <p >{{ item.letter_of_thanks }}</p>
                    </div>
                {% endif %}
            {% endfor %}
        </div>
    </div>

</body>
</html>
index》html

 

 

  

  

  

  

 

posted @ 2016-09-21 23:34  众里寻,阑珊处  阅读(227)  评论(0编辑  收藏  举报
返回顶部