1、配置index
主url
from django.contrib import admin from django.urls import path, re_path, include urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^app01/', include(('app01.urls', 'app01'))), ]
app01 的url
from django.urls import path, re_path, include from app01 import views urlpatterns = [ re_path(r'^index/$', views.index, name='index') ]
views
from django.shortcuts import render, HttpResponse def index(request): return HttpResponse('<h1>app01 index</h1>')
2、get post方法
view.py
def login(request): print('method:', request.method) return render(request, 'login.html') # render方法的本质是渲染html, 然后调用HttpResponse 返回字符串
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {#<form action="http://127.0.0.1:8000/app01/login/" method="post">#} {#<form action="" method="post"> 不写的话,默认当前目录 #} <form action="/app01/login/" method="post"> username <input type="text" name="user"> password <input type="text" name="pwd"> <input type="submit"> </form> </body> </html>
4 .request属性
""" http://127.0.0.1:8000/app01/login/?year=2003&month=08 url: 协议://IP:port /路径 ?get请求数据 """
def login(request): print('method:', request.method) print(request.GET) # 打印get方法传过来的数据 print(request.POST) # 打印post方法data print(request.GET.get('year')) # dict的get方法 print(request.POST.get('user')) # dict的get方法 print(request.path) # 打印路径 print(request.get_full_path()) # 返回 path,如果可以将加上查询字符串。 return render(request, 'login.html') # render方法的本质是渲染html, 然后调用HttpResponse 返回字符串
6、视图响应对象
HttpResponse
from django.shortcuts import render, HttpResponse def index(request): return HttpResponse('<h1>app01 index</h1>')
render
url