Fungsi jalan pintas Django¶
The package django.shortcuts collects helper functions and classes that
"span" multiple levels of MVC. In other words, these functions/classes
introduce controlled coupling for convenience's sake.
render()¶
- render(request, template_name, context=None, content_type=None, status=None, using=None)[sumber]¶
Combines a given template with a given context dictionary and returns an
HttpResponseobject with that rendered text.Django does not provide a shortcut function which returns a
TemplateResponsebecause the constructor ofTemplateResponseoffers the same level of convenience asrender().
Argumen dibutuhkan¶
requestObjek peminta digunakan untuk membangkitkan tanggapa ini.
template_nameThe full name of a template to use or sequence of template names. If a sequence is given, the first template that exists will be used. See the template loading documentation for more information on how templates are found.
Argumen pilihan¶
contextNilai kamus untuk ditambah ke konteks cetakan. Secara awalan, ini adalah kamus kosong. Jika nilai di kamus adalah callable, tampilan akan memanggilnya sesaat sebelum membangun cetakan.
content_typeJenis MIME digunakan untuk menghasilkan dokumen. Awalan menjadi
'text/html'.statusKode status untuk tanggapan. Awalan menjadi
200.usingNAMEdari mesin cetakan untuk digunakan untuk memuat cetakan.
Contoh¶
Contoh berikut membangun cetakan myapp/index.html dengan jenis MIME application/xhtml+xml:
from django.shortcuts import render
def my_view(request):
# View code here...
return render(
request,
"myapp/index.html",
{
"foo": "bar",
},
content_type="application/xhtml+xml",
)
Contoh ini setara pada:
from django.http import HttpResponse
from django.template import loader
def my_view(request):
# View code here...
t = loader.get_template("myapp/index.html")
c = {"foo": "bar"}
return HttpResponse(t.render(c, request), content_type="application/xhtml+xml")
redirect()¶
- redirect(to, *args, permanent=False, preserve_request=False, **kwargs)[sumber]¶
Mengembalikan
HttpResponseRedirectke URL yang sesuai untuk argument dilewatkan.Argumen dapat menjadi:
Sebuah model: fungsi model's
get_absolute_url()akan dipanggil.Nama tampilan, kemungkinan dengan argumen:
reverse()akan digunakan untuk membalikkan-menyelesaikan nama.Sebuah URL mutlak atau relatif, yang akan digunakan dengan adanya untuk pengalihan lokasi.
By default, a temporary redirect is issued with a 302 status code. If
permanent=True, a permanent redirect is issued with a 301 status code.If
preserve_request=True, the response instructs the user agent to preserve the method and body of the original request when issuing the redirect. In this case, temporary redirects use a 307 status code, and permanent redirects use a 308 status code. This is better illustrated in the following table:permanent
preserve_request
HTTP status code
TrueFalse301
FalseFalse302
FalseTrue307
TrueTrue308
Changed in Django 5.2:The argument
preserve_requestwas added.
Contoh¶
Anda dapat menggunakan fungsi redirect() dalam sejumlah cara.
Dengan melewatkan beberapa objek; metode objek
get_absolute_url()akan dipanggil untuk mencari tahu URL pengalihan:from django.shortcuts import redirect def my_view(request): ... obj = MyModel.objects.get(...) return redirect(obj)
Dengan melewatkan nama dari tampilan dan pilihan beberapa popsisi atau argumen kata kunci; URL akan dibalikkan menggunakan metode
reverse():def my_view(request): ... return redirect("some-view-name", foo="bar")
Dengan melewatkan URL kode keras ke pengalihan pada:
def my_view(request): ... return redirect("/some/url/")
Ini juga bekerja dengan URL penuh:
def my_view(request): ... return redirect("https://example.com/")
Secara awalan, redirect() mengembalikan peralihan sementara. Semua dari formulir diatas menerima argumen permanent; jika disetel menjadi True pengalihan tetap akan dikembalikan:
def my_view(request):
...
obj = MyModel.objects.get(...)
return redirect(obj, permanent=True)
Additionally, the preserve_request argument can be used to preserve the
original HTTP method:
def my_view(request):
# ...
obj = MyModel.objects.get(...)
if request.method in ("POST", "PUT"):
# Redirection preserves the original request method.
return redirect(obj, preserve_request=True)
# ...
get_object_or_404()¶
- aget_object_or_404(klass, *args, **kwargs)¶
Asynchronous version:
aget_object_or_404()Memanggil
get()pada pengelola model diberikan, tetapi itu memunculkanHttp404daripada eksepsi modelDoesNotExist.
Argumen¶
Contoh¶
Contoh berikut mendapatkan objek dengan primary key 1 dari MyModel:
from django.shortcuts import get_object_or_404
def my_view(request):
obj = get_object_or_404(MyModel, pk=1)
Contoh ini setara pada:
from django.http import Http404
def my_view(request):
try:
obj = MyModel.objects.get(pk=1)
except MyModel.DoesNotExist:
raise Http404("No MyModel matches the given query.")
Kasus penggunaan paling umum adalah melewatkan Model, seperti ditunjukkan diatas. Bagaimanapun, anda dapat juga melewatkan instance QuerySet:
queryset = Book.objects.filter(title__startswith="M")
get_object_or_404(queryset, pk=1)
Contoh di atas agak dibuat-buat karena setara dengan melakukan:
get_object_or_404(Book, title__startswith="M", pk=1)
tetapi itu dapat berguna jika anda melewati variabel queryset dari tempat lain.
Akhirnya, anda dapat juga menggunakan Manager. Ini berguna untuk contoh jika anda mempunyai custom manager:
get_object_or_404(Book.dahl_objects, title="Matilda")
Anda dapat juga menggunakan related managers:
author = Author.objects.get(name="Roald Dahl")
get_object_or_404(author.book_set, title="Matilda")
Catat: Seperti get(), eksepsi MultipleObjectsReturned akan dimunculkan jika lebih dari satu objek ditemukan.
get_list_or_404()¶
- aget_list_or_404(klass, *args, **kwargs)¶
Asynchronous version:
aget_list_or_404()Mengembalikan hasil dari
filter()pada pengelola model yang diberikan dilemparkan ke list, memunculkanHttp404jika menghasilkan list adalah kosong.
Argumen¶
Contoh¶
Contoh berikut mendapatkan semua objek diterbitkan dari MyModel:
from django.shortcuts import get_list_or_404
def my_view(request):
my_objects = get_list_or_404(MyModel, published=True)
Contoh ini setara pada:
from django.http import Http404
def my_view(request):
my_objects = list(MyModel.objects.filter(published=True))
if not my_objects:
raise Http404("No MyModel matches the given query.")