Django学习路3

1.打开 Data Source
alt insert 打开 Data Source 找到 db.sqlite3 确定
Download 下载后 TestConnection 测试是否成功
2.项目下的 urls.py 文件
    urlpatterns 匹配网页集合
    写法 url(正则,views.函数)
     url(r'函数名/',views.函数) 最好是斜线结尾
      views 来自创建的 app 中,需要导入
       views.py 内定义函数 def 函数名(request):pass
        HttpResponse("内容") 进行响应
         内容可以是 HTML 代码(a标签,h1标题等等)
        render(request,"模板名字")
         render(request,"index.html")
          直接写文件名.html
3.进行访问 127.0.0.1:8000/函数名
4.templates 包含 HTML 文件
    显示数据 -> 在 urls.py 中添加
     url(r"函数名/",views.函数名)
5.让项目和创建的 App 连接
    在项目的 settings.py 文件的 INSTALLED_APPS 中添加 创建的 APP 名字
    例:INSTALLED_APPS = ['...','...','App']
6.SyntaxError: Generator expression must be parenthesized
打开 ~/HanyProject/venv/lib/python3.7/site-packages/django/contrib/admin 的 widgets.py 文件 到 151 行 将params.items() 后面的逗号去掉
7.升级 Django 到 2.x 版本
8.将 templates 加入到 settings 的 TEMPLATES 中 的 'DIRS''DIRS': [os.path.join(BASE_DIR, 'templates')]
9.出现错误先看日志文件

urls.py 文件


from django.contrib import admin
from django.urls import path

from Hanyapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'sayHello/',views.sayHello),
    path(r'goBaiDu/',views.goBaiDu),
    path(r'index/',views.index)
]

views.py


from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.

def sayHello(request):
    return HttpResponse("<h3> 你好,世界 <h3>")

def goBaiDu(request):
    return HttpResponse("<a href = 'www.baidu.com'>百度</a>")

def index(request):
    return render(request,'index.html')

settings.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Hanyapp'
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    用户名:<input type="text" placeholder="请输入用户名">
    密码:<input type="password">
</body>
</html>

 

 

 


2020-04-26

 

 

原文地址:https://www.cnblogs.com/hany-postq473111315/p/12778795.html