返回顶部

纯手撸Django Web框架实现网站

  纯手撸Django Web框架实现网站

二十分钟小白玩转Django web网站的部署。

 

Django Web框架包含了URL处理、模型、视图、模版四个主要部分。

  • URL处理负责用户请求到视图的映射
  • 视图用于处理用户逻辑
  • 模型用于映射Python对象和数据对象
  • 模板用于展示特定信息的样式给用户

 

1、创建项目

$ django-admin startproject mysite
$ cd mysite/

 settings.py   网站的设置
 urls.py        网站处理请求

 

 

 

2、创建应用

$ python manage.py  startapp myweb

 admin.py    管理功能
 apps.py       保存应用程序基本配置
 models.py   模型,
 tests.py   
 urls.py    不存在需单独手动创建,
 views.py   视图
templates/web.html  模板和文件需单独手动创建

 

 

 

2.1 处理URL

mysite/urls.py >> myweb/urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.urls')),
]

### mysite/mysite/urls.py
from django.contrib import admin
from django.urls import path

from django.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),   #将请求转发给app进行处理
    path('myweb', include('myweb.urls')),
]

###  mysite/myweb/urls.py
from django.urls import path
from  . import views

urlpatterns = [
    path('', views.index, name='index'),  #'',在localhost:8080/myweb后面不在添加path,需要时可在添加等同于localhost:8080/myweb/xxx
]


### mysite/myweb/views.py
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse

# 接收用户的请求,采用标准的httpreponse返回数据
def index(request):
    # 处理模型,指定模板
    return HttpResponse('Hello Django')

 

2.2 视图和模板

后续会使用模板目前只返回字符串

{% if lastes_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available</p>
{% endfor %}

 

 

3 运行Django

python manage.py  runserver 0.0.0.0:8080

http://localhost:8080/myweb

 

4 创建管理页面的用户密码

#需要运行迁移以更改管理员用户名和密码
python manage.py migrate

#编辑用户名和密码 
$ python manage.py createsuperuser
Username (leave blank to use 'administrator'): wei
Email address: wei@11.com
Password: 
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.


#创建一个超级用户来访问django 
$ python manage.py createsuperuser
Username (leave blank to use 'administrator'): admin
Email address: admin@11.com
Password: 
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.



#再次运行Django即可
 python manage.py  runserver 0.0.0.0:8080

 

5 访问测试

5.1 访问制定URL

http://localhost:8080/myweb

 

5.2 访问管理站点

http://localhost:8080/admin

 

 

 

 

 

 

posted @ 2023-07-22 23:52  九尾cat  阅读(86)  评论(0编辑  收藏  举报