Django comes with an optional redirects application. It lets you store simple
redirects in a database and handles the redirecting for you. It uses the HTTP
response status code 301 Moved Permanently by default.
Untuk memasang aplikasi pengalihan, ikuti langkah-langkah ini:
Pastikan bahwa kerangka kerja django.contrib.sites is installed.
Tambah pengaturan 'django.contrib.redirects' to your INSTALLED_APPS.
Tambah 'django.contrib.redirects.middleware.RedirectFallbackMiddleware' ke pengaturan MIDDLEWARE anda.
Jalankan perintah manage.py migrate.
manage.py migrate creates a django_redirect table in your database. This
is a simple lookup table with site_id, old_path and new_path fields.
The RedirectFallbackMiddleware
does all of the work. Each time any Django application raises a 404
error, this middleware checks the redirects database for the requested
URL as a last resort. Specifically, it checks for a redirect with the
given old_path with a site ID that corresponds to the
SITE_ID setting.
new_path is not empty, it redirects to
new_path using a 301 (“Moved Permanently”) redirect. You can subclass
RedirectFallbackMiddleware
and set
response_redirect_class
to django.http.HttpResponseRedirect to use a
302 Moved Temporarily redirect instead.Jika itu menemukan kecocokan, dan new_path adalah kosong, itu mengirim sebuah 410 (“Gone”) kepala HTTP dan tanggapan (kurang-isi) kosong.
The middleware only gets activated for 404s – not for 500s or responses of any other status code.
Note that the order of MIDDLEWARE matters. Generally, you can put
RedirectFallbackMiddleware at the
end of the list, because it’s a last resort.
Untuk lebih pada middleware, baca dokumentasi middleware.
Jika anda telah mengaktifkan antarmuka admin Django otomatis, anda harus melihat bagian “Redirects” pada halaman indeks admin. Sunting pengalihan ketika anda menyunting obyek lain apapun di sistem.
models.Redirect¶Pengalihan adalah diwakili oleh Django model standar, yang tinggal di django/contrib/redirects/models.py. Anda dapat mengakses pengalihan obyek melalui Django database API.
middleware.RedirectFallbackMiddleware¶Anda dapat merubah kelas-kelas HttpResponse digunakan oleh middleware dengan membuat sebuah subkelas dari RedirectFallbackMiddleware dan terutama response_gone_class dan/atau response_redirect_class.
response_gone_class¶Kelas HttpResponse digunakan ketika Redirect tidak ditemukan untuk jalur yang diminta atau mempunyai nilai new_path kosong.
Awalan pada HttpResponseGone.
response_redirect_class¶Kelas HttpResponse yang mengangani pengalihan.
Awalan pada HttpResponsePermanentRedirect.
Apr 04, 2017