django常用接收,返回方法和反向解析的使用,json返回,获取一键多值,重定向,返回404


from django.shortcuts import render,redirect
from django.http import HttpResponse,Http404,HttpResponseNotFound,JsonResponse
from django.core.urlresolvers import reverse

from . models import Users,Stu,StuInfo,ClassInfo,Books,Tags


#返回json数据
def index(request):

    import json
    
    # 响应 模板文件
    # return HttpResponse('hello world')
    # data = {'name':'zahngsan','age':20,'sex':'男'}
    # data = [
    #     {'name':'zahngsan','age':20,'sex':'男'},
    #     {'name':'王五','age':22,'sex':'男'},
    # ]
    

    # 使用python的json 转为json格式再返回
    # content-type: html
    # return HttpResponse(json.dumps(data))

    # 返回json数据  content-type: json
    return JsonResponse(data,safe=False)

# 常用的请求,返回方法和反向解析的使用
def viewsdemo(request):
    # 直接返回一个404,没有去加载404的模板页面
    # return HttpResponseNotFound('<h1>Page not found</h1>')

    # 可以直接返回一个status状态码
    # return HttpResponse(status=403)

    # 返回一个404的错误页面
    # raise Http404("Poll does not exist")


    # 重定向 redirect 参数 重定向的url地址
    # return redirect(reverse('ontoone')) 
	
    # context = {'msg':'恭喜注册成功,即将跳转到登录页','u':reverse('ontoone')} 

    # return render(request,'info.html',context) 
# 这个context传输到info页面直接使用 {{ msg  }}  #链接用这个方法接收  <a> href = "{{ u }}"</a>


    # 请求对象  request ==> HttpRequest

    # 获取当前的请求地址 path路径
    # print(request.path)
    # 获取请求方式
    # print(request.method)

    # GET是请求对象的一个属性,但是GET本身也是一个类字典的对象
    # print(request.GET)
    # 获取GET中参数 如果请求不到返回null,第二个参数可以设置默认值
    # print(request.GET.get('a','1'))
	#这个方法,如果是空值会报错,推荐使用上一个方法
    # print(request.GET['a'])

    # POST和GET一样
    return HttpResponse('视图的操作')

# 一键多值的参数请求方式 get和post一样   使用此方法getlist()
def form(request):
    # 判断请求的方式
    if request.method == 'GET':
        # 加载一个表单模板
        return render(request,'form.html')
    else:
        # 接收表单数据
		# 一键多值的方法来接收,get和post接收方法一样
        # print(request.POST.getlist('hobby'))
        #### print(request.GET.getlist('a'))

        return HttpResponse('接收表单数据')

猜你喜欢

转载自blog.csdn.net/Doraemon_meow_meow/article/details/90201280