定製django admin頁面的跳轉

在django admin的 change_view,  add_view和delete_view頁面,若是想讓頁面完成操做後跳轉到咱們想去的url,該怎麼作html

默認django admin會跳轉到changelist_view頁面django

 

------------------------------瀏覽器

下面的代碼是django1.6的服務器

 

下面是一個可行的作法,寫admin model的時候重寫父類admin.ModelAdmin的change_view 方法app

from django.contrib import admin
class MyAdmin(admin.ModelAdmin):
    def change_view(self, request, object_id, form_url='', extra_context=None):
        result_template = super(MyAdmin, self).change_view(request, object_id, form_url, extra_context)
        result_template['location'] = '/dest/url'
        return result_template           

 

能夠看到,就是調用ModelAdmin的change_view獲得結果,而後給 result_template作了一個這個操做函數

 result_template['location'] = '/dest/url'

而後返回url

 

爲何這樣可行? 咱們看看發生了什麼spa

 

咱們重寫change_view,固然參數必須和父類同樣了code

 

首先調用了父類ModelAdmin.change_view的這個函數,這個函數返回了什麼呢orm

追溯一下源代碼,它返回的是一個TemplateResponse對象, 是經過調用 ModelAdmin.render_change_form()

 

return TemplateResponse(request, form_template or [
    "admin/%s/%s/change_form.html" % (app_label, opts.model_name), 
    "admin/%s/change_form.html" % app_label,
    "admin/change_form.html"        
 ], context, current_app=self.admin_site.name)     

 

那麼接下來咱們看看TemplateResponse

 其實有這樣的派生關係: TemplateResponse <----  SimpleTemplage  <-----HttpRespone  <--- HttpResponseBase

 

HttpResponse裏實現了 

def __setitem__(self, header, value):
    header = self._convert_to_charset(header, 'ascii')
    value = self._convert_to_charset(value, 'latin-1', mime_encode=True)
    self._headers[header.lower()] = (header, value)

 

而若是一個類實現了 __setitem__,  那麼[] 操做符就會去調用這個函數(至關於C++中的重載)

result_template['location'] = '/dest/url'

 

因此上面這行代碼就在服務器返回的Response的header中寫入了location, 而瀏覽器收到的Http Response的header中若是有location,就會跳轉到location指定的 url

 

-------------------------------------------------------

 

可是我還發現了一個現象, 當進入到一個model item的change_view界面時,也就是GET請求這個url,雖然服務端返回了location,可是瀏覽器沒有跳轉,多是由於當前有form須要提交.

 而在change_view界面修改完後, 點擊提交表單,瀏覽器收到服務端的location後,就發生了跳轉.

相關文章
相關標籤/搜索