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 对象。

  1. path = r"C:\Users\18309\\img\123.jpg"
  2. file_one = open(path, "rb")
  3. return HttpResponse(file_one.read(), content_type='image/jpg')

redirect

redirect(to, *args, permanent=False, **kwargs)

利用URL反向解析,将使用reverse方法来进行反向解析

  1. return redirect('some-view-name', foo='bar')

利用硬编码

  1. return redirect('/some/url/')

利用完整的URL

  1. return redirect('https://example.com/')

get_object_or_404

相当于get方法跟Http404的组合

get_list_or_404

相当于filter方法跟Http404的组合

  1. from django.shortcuts import get_object_or_404,render
  2. from .models import Question
  3. def detail(request, question_id):
  4. question = get_object_or_404(Question, id=question_id)
  5. return render(request, 'news/detail.html', {'question': question})

等价于

  1. def detail(request, question_id):
  2. try:
  3. question = Question.objects.get(id=question_id)
  4. except Question.DoesNotExist:
  5. raise Http404("Question does not exist")
  6. return render(request, 'polls/detail.html', {'question': question})

require_GET

  1. @require_GET
  2. def show(request):
  3. return HttpResponse('Hello')