Django理解

来源:互联网 发布:中国移动网络制式 编辑:程序博客网 时间:2024/06/05 18:07


manager.py中


if __name__ == "__main__":    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cwBlog.settings")    from django.core.management import execute_from_command_line    execute_from_command_line(sys.argv)

加载settings配置文件

配置文件中初始化数据库,安装app匹配,模版路径。url根目录。中间件匹配。

DATABASES = {    'default': {        'ENGINE': 'django.db.backends.mysql',   # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.        'NAME': 'cwBlog',                      # Or path to database file if using sqlite3.        # The following settings are not used with sqlite3:        'USER': 'root',        'PASSWORD': '258841679',        'HOST': '127.0.0.1',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.        'PORT': '3306',                      # Set to empty string for default.    }}
TEMPLATE_DIRS = (    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".    # Always use forward slashes, even on Windows.    # Don't forget to use absolute paths, not relative paths.    "cwBlog/html/template/")ROOT_URLCONF = 'cwBlog.urls'INSTALLED_APPS = (    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.sites',    'django.contrib.messages',    'django.contrib.staticfiles',    'cwBlog',    # Uncomment the next line to enable the admin:    'django.contrib.admin',    # Uncomment the next line to enable admin documentation:    # 'django.contrib.admindocs',)

当1个http请求产生。

通过urls.py解析路径。并投递到对应的view视图函数中。


urlpatterns = patterns('',    # Examples:    # url(r'^$', 'cwBlog.views.home', name='home'),    # url(r'^cwBlog/', include('cwBlog.foo.urls')),    # Uncomment the admin/doc line below to enable admin documentation:    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),    # Uncomment the next line to enable the admin:    url(r'^admin/', include(admin.site.urls)),    url(r'^$', blog),    url(r'^blog/$', blog),)


在视图函数中,加载数据模型,和模版。得到需要显示的数据以后,重绘模版。返回响应.

from django.template import loader, Contextfrom django.http import HttpResponsefrom cwBlog.models import BlogPostdef blog(request):    posts = BlogPost.objects.all()    t = loader.get_template('blog.html')    c = Context({'posts' : posts})    return HttpResponse(t.render(c))

具体解析模版

其中post.timestamp | date:""

|表示后面接上过滤器

date格式化

{% extends "base.html" %}{% block content %}    {% for post in posts %}        <h2>{{ post.title }}</h2>        <p>{{ post.timestamp | date:"1, F jS" }}</p>        <p>{{ post.body }}</p>    {% endfor %}{% endblock %}


原创粉丝点击