Django2 模版

urls.py

from django.urls import path, include

urlpatterns = [
    # path('admin/', admin.site.urls),
    path("user/",include("App.urls")),
    path("hello/",include("App02.urls")),
]

App.urls

from django.urls import path, re_path

from App import views
app_name = "App"  # 应用的名空间
urlpatterns = [
    path('', views.index, name='index'),
    path('show/<name>/<int:age>/',views.show, name='show'),
    re_path(r'^call/(\d{4}-\d{8})/$',views.call,name='call'),

    # 请求对象===响应对象
    path('req/',views.req_res,name='reqres'),
]

App.views

from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.shortcuts import render, redirect


# Create your views here.
from django.urls import reverse


def index(request):
    return HttpResponse("首页")


def show(request,name,age):
    return HttpResponse(name + ":"+str(age))


def call(request,phone):
    # return HttpResponse(phone)
    return render(request,'call.html')


def req_res(request):
    print(request.method)
    # print(request.GET.get("username")) # 如果username不存在,会返回None
    # print(request.GET["username"])  # 如果username不存在,会报错
    # url只能ascii码,不是ascii必须要转义
    # print(request.GET.getlist('username'))
    #post
    # print(request.POST.getlist('username'))

    # print(request.path)
    # 来源页面
    # http://127.0.0.1:9001/user/call/0998-12345678/
    # print(request.META.get("HTTP_REFERER"))
    # print(request.META.get("REMOTE_ADDR"))

    # 响应对象
    # res = HttpResponse("ok")
    # res.status_code = 300
    # res.content = b"123"

    # res = render(request,'call.html')
    # return res

    # JsonResponse
    # return JsonResponse({'code':1})
    # return JsonResponse([1,2,3,4,5],safe=False)

    # 重定向
    # return HttpResponseRedirect("/user/")
    # return redirect("/user/")
    # return redirect("/user/show/{}/{}/".format('tom',30))
    # return redirect("/user/show/admin/50/")
    # 应用内跳转可以不写http://127.0.0.1:9003
    # return redirect("http://127.0.0.1:9003/user/show/admin/50/")
    # 应用外跳转
    # return redirect("https://www.baidu.com/")

    # 反向定位:由应用命名空间:name来确定路由
    # print(reverse("App:index"))
    # return redirect(reverse("App:index"))  # 不带参数

    # 如果参数有名字,必须使用关键字传参的方式
    # print(reverse("App:show",kwargs={'name':'admin','age':20}))
    # return redirect(reverse("App:show",kwargs={'name':'admin','age':20}))
    # print(1 / 0)
    print(reverse("App:call",args=('0311-58931234',)))
    return redirect(reverse("App:call",args=('0311-58931234',)))

App02.urls

from django.urls import path, re_path

from App02 import views
app_name = "App02"  # 应用的名空间
urlpatterns = [
    path("",views.index, name='index'),
    path("example/",views.process_template, name='example'),
    path("render/",views.load_template, name='render'),
    # 变量
    path('var/',views.handle_var, name='var'),
    # 过滤器
    path('filter/',views.handle_filter, name='filter'),
    # 内建标签
    path('tag/',views.handle_tag, name='tag'),
    #csrf保护
    path("csrf/",views.login, name='login'),
    path('ajax/',views.handle_ajax,name='ajax'),
]

App02.views

from datetime import datetime

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

# Create your views here.
from django.template import loader
from django.views.decorators.csrf import csrf_exempt


def index(request):

    # html = """
    # <html>
    # <head>
    # <meta charset='utf-8'>
    # </head>
    # <body>
    # <table border='1' cellspacing='0'>
    #
    # """
    # other = """
    # </table>
    # </body>
    # </html>
    # """
    # users = [{'username':'admin'},{'username':'hello'}]
    # for user in users:
    #     html += "<tr><td>"+user['username']+"</td></tr>"
    # html += other

    # return HttpResponse(html)

    # 使用模板引擎
    users = [{'username': 'admin'}, {'username': 'hello'}]
    return render(request,"app02/index.html",context=locals())


def process_template(request):
    return render(request,"example.html")


def load_template(request):
    # # 1.加载模板文件,生成模板对象
    # obj = loader.get_template("example.html")
    # print(obj,type(obj))
    # # 2.渲染
    # res = obj.render({'name':'admin'})
    # # 渲染的结果生成html源文件(字符串)
    # print(res)
    # return HttpResponse(res)

    # render加载和渲染一块进行,是一种快捷方式
    return render(request,'example.html',context={'name':'admin'})


def handle_var(request):
    num = 10
    name = "伟大的意大利左后卫"
    students = [10,20,30,[50,60]]
    student = {'name':'马尔蒂尼','age':30}
    return render(request,"变量.html",locals())


def handle_filter(request):
    num = 10
    name = "伟大的意大利左后卫"
    # age = None
    t1 = datetime.now()
    content = "<h1>自动转义功能,把<和>转义普通字符</h1>"
    return render(request,'过滤器.html',locals())


def handle_tag(request):
    l1 = [10,20,30,40]
    num = 21
    return render(request,'tag.html',locals())

# 局部禁用csrf保护
@csrf_exempt
def login(request):
    if request.method == "POST":
        print(request.POST.get('username'))

    return render(request,"login.html")


def handle_ajax(request):
    print(1111)
    if request.is_ajax():
        return JsonResponse({"code":0,'msg':"登录成功"})
    print(2222)
    return render(request,"ajax1.html")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值