django03

根据实体模型进行模块拆分

如当我创建了两个模块:python manage.py startapp app
python manage.py startapp goods
那么我就会获得2个模块分别拥有models.py views.py urls.py
(虚拟环境创建: virtualenv --no-site-packages -p python.exe路径 环境名
安装: pip install django==2.1.7
需要再虚拟环境被激活(env的Script文件夹下activate)的情况下才能使用此命令
创建项目django-admin startproject 项目名day01
day01.urls.py配置总的模块路由

from django.urls import path, re_path, include
urlpatterns = [

    # 注意 app和goods后面的/ ,在访问对应的模块的时候需要加上对应的前缀

    path('app/', include('app.urls')),
    path('goods/', include('goods.urls'))
]

例如在app.urls中页面的配置信息有

path('str_params/<str:name>/', str_params),
# 解析path中的正则表达式
re_path('year_params/(\d+)/(\d+)/(\d+)/', year_params)
# 地址栏传参的时候不是按顺序而是给定具体参数
re_path('p_params/(?P<year>\d+)/(?p<month>\d+)/(?P<day>\d+)', p_params)

对应的app.views

def str_params(request, name):
  if request.method == 'GET':
    return Httpresponse('name %s' % name)
 def index(request):
    if request.method == 'GET':
        # TODO:render(request)
        stus =Student.objects.all()
        content_h2 = '<h2>hello world</h2>'
        return render(request, 'index.html' ,
                      {'students':stus,  'content_h2':content_h2})

index.html如下

{% block content %}
    {{ content_h2 | safe }}
    <table>
        <thead>
            <th>编号</th>
            <th>姓名</th>
            <th>手机号</th>
            <th>班级名</th>
            <th>课程名</th>
            <th>第一个课程</th>
            <th>创建时间</th>
        </thead>
    <tbody>
    {% for stu in students %}
        <tr>
            <td>{{ forloop.counter }}</td>
            <td {% ifequal forloop.counter 1 %} style="color: yellowgreen" {% endifequal %}>{{ stu.s_name }}</td>
            <td>{{ stu.stuinfo.phone }}</td>
            <td>{{ stu.grade.g_name }}</td>
            <td>
                {%  for cou in stu.course.all %}
                    {{ cou.c_name }}
                {% endfor %}
            </td>
            <td>
                {{ stu.course.all.0.c_name }}
            </td>
            <td>{{ stu.create_time }}</td>
        </tr>
    {% endfor %}
    </tbody>
    </table>
{% endblock %}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • PythonWeb框架要点、Django介绍、工程搭建、配置、静态文件与路由 1.Python Web 框架要点 ...
    Cestine阅读 1,550评论 0 6
  • (一)、启动服务器 (二)、创建数据库表 或 更改数据库表或字段 Django 1.7.1及以上 用以下命令 1....
    夏天夏星阅读 5,685评论 0 17
  • Django的来历:python开发的! long long long years ago!劳伦斯出版集团新闻 网...
    JAguys阅读 358评论 0 0
  • 上面这两个图片是ORM对象关系映射的关系理解。 django框架 一、简介 web框架 具体介绍django之前,...
    AAA年华阅读 2,378评论 0 2
  • 1.安装虚拟环境 pip install virtualenvwrapper 安装完之后设置一下环境变量WORK_...
    假装我不帅阅读 1,546评论 0 0