当前位置 博文首页 > Weiyaner的博客:Django web开发1(环境部署+第一个web程序)

    Weiyaner的博客:Django web开发1(环境部署+第一个web程序)

    作者:[db:作者] 时间:2021-07-07 18:41

    通过Django框架进行web开发1–环境部署

    1.下载Django

    pip install django==1.11.7 -i https://pypi.douban.com/simple
    

    2.在pycharm中打开Django框架

    • 第一步:新建Django项目,需要配置python环境,找到下载的py.exe
    • 第二步,应用命名,然后创建即可
      在这里插入图片描述

    3.初识Django界面

    在Django的哲学中,我们有两个重要的概念:

    • app:是一个可以做完成某件事情的Web应用程序。一个应用程序通常由一组models(数据库表),views(视图),templates(模板),tests(测试) 组成。
    • project:是配置和应用程序的集合。一个项目可以由多个应用程序或一个应用程序组成。
    • 每个文件的作用:
    • migrations/:在这个文件夹里,Django会存储一些文件以跟踪你在models.py文件中创建的变更,用来保持数据库models.py的同步。
    • admin.py:这个文件为一个django内置的应用程序Django Admin的配置文件。
    • apps.py:这是应用程序本身的配置文件。
    • models.py:这里是我们定义Web应用程序数据实例的地方。models会由Django自动转换为数据库表。
    • tests.py:这个文件用来写当前应用程序的单元测试。

    在这里插入图片描述

    • views.py:这是我们处理Web应用程序请求(request)/响应(resopnse)周期的文件。

      在view文件中,可以直接编写html程序,也可以在templates文件夹中新建html文件,在view中直接调用

    from __future__ import unicode_literals
    from django.http import HttpResponse
    from django.shortcuts import render
    # Create your views here.
    from superweiyan.models import Students
    
    def index(request):
        return render(request,'1.html')
    def index2(request):
        return HttpResponse('<h1>一级标题<h2>'
                             '<h2>二级标题<h2>'
                             '<h3>三级标题<h3>')
    def weather(request):
        return render(request, 'weather.html')  #无论是HttpResponse还是render,都是一种响应
    
    • 还有最重要的urls.py
      当我们在view中定义了多种视图时,即编写了相关的Html文件,需要告诉Django怎么调用,就需要在urls.py文件中进行编写
    from django.conf.urls import url
    from django.contrib import admin
    from superweiyan import views
    
    urlpatterns = {
        url(r'^admin/', admin.site.urls),
        url(r'index', views.index),
        url(r'index2', views.index2),
        url(r'weather', views.weather),
        url(r'getstudents', views.getstudents),
    } 
    

    4.运行程序

    点击运行后,出现以下界面:

    System check identified no issues (0 silenced).
    June 25, 2019 - 10:57:03
    Django version 1.11.7, using settings ‘Helloworld.settings’
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CTRL-BREAK.

    其中,打开那个网址,在后面输入urls.py文件中定义的网页名称,即出现以下的界面
    在这里插入图片描述
    那么到此为止,第一个界面的编写完成了,下一篇说明数据库的连接

    cs
    下一篇:没有了