djnago.shortcuts
https://docs.djangoproject.com/zh-hans/3.2/topics/http/shortcuts/
Http404, HttpResponse, reander, reverse, redirect, get_object_or_404, get_list_or_404
render
render(request, template_name, context=None, content_type=None, status=None, using=None)
将给定的模板与给定的上下文字典组合在一起,并以渲染的文本返回一个 HttpResponse 对象。
path = r"C:\Users\18309\\img\123.jpg"
file_one = open(path, "rb")
return HttpResponse(file_one.read(), content_type='image/jpg')
redirect
redirect(to, *args, permanent=False, **kwargs)
利用URL反向解析,将使用reverse方法来进行反向解析
return redirect('some-view-name', foo='bar')
利用硬编码
return redirect('/some/url/')
利用完整的URL
return redirect('https://example.com/')
get_object_or_404
get_list_or_404
相当于filter方法跟Http404的组合
from django.shortcuts import get_object_or_404,render
from .models import Question
def detail(request, question_id):
question = get_object_or_404(Question, id=question_id)
return render(request, 'news/detail.html', {'question': question})
等价于
def detail(request, question_id):
try:
question = Question.objects.get(id=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})
require_GET
@require_GET
def show(request):
return HttpResponse('Hello')