亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用模板覆蓋更改 django 管理列表中的模型對象 url

使用模板覆蓋更改 django 管理列表中的模型對象 url

郎朗坤 2022-06-28 10:27:35
假設我有一個 Category 的模型,并且它已經在 admin.py 中聲明了。我想使用 Django 模板覆蓋做兩件事。在“添加類別+ ”附近的右側添加一個按鈕,該按鈕僅在“類別列表”頁面上可見,并將我帶到另一個 URL。覆蓋 Category 對象的 URL,以便單擊列表上的每個單獨的類別會轉到相應的 URL# models.pyclass Category(models.Model):    name = models.CharField(max_length=50, null=True, blank=False)    LANGUAGE_ENGLISH = 'en'    LANGUAGE_FRENCH = 'fr'    LANGUAGES = ((LANGUAGE_ENGLISH, 'English'),(LANGUAGE_FRENCH, 'French'),)    language = models.CharField(max_length=12, default=LANGUAGE_ENGLISH, choices=LANGUAGES, blank=False)    created_at = models.DateTimeField(auto_now_add=True)# [email protected](Category)class CategoryAdmin(admin.ModelAdmin):    list_display = ('name', 'language', 'created_at')    list_filter = ('created_at', 'language')    search_fields = ('name',)    date_hierarchy = 'created_at'    ordering = ['-created_at']管理面板中的類別 在這里,單擊 Lifestyle 或 Travel 應該會將我帶到兩個外部 URL。
查看完整描述

1 回答

?
德瑪西亞99

TA貢獻1770條經驗 獲得超3個贊

第一個解決方案:

手動覆蓋list_display_links和更改您的字段

這是一個兩步的過程。首先,我們需要改變get_list_display_links默認行為。


查看 django 的文檔和源代碼,您會發現它最終會使用list_display. 在您的管理課程中:


@admin.register(Category)

class CategoryAdmin(admin.ModelAdmin):

    list_display = ('name', 'language', 'created_at')

    list_filter = ('created_at', 'language')

    list_display_links = [] #< With this, you still can add up a link to your original admin

    search_fields = ('name',)

    date_hierarchy = 'created_at'

    ordering = ['-created_at']


    def get_list_display_links(self, request, list_display):

        """

        Return a sequence containing the fields to be displayed as links

        on the changelist. The list_display parameter is the list of fields

        returned by get_list_display().

        """

        if self.list_display_links or self.list_display_links is None or not list_display:

            # We make sure you still add your admin's links if you explicitly declare `list_display_links`

            return self.list_display_links 

        else:

            # We return empty list instead of `list_display[:1]`

            # if no `list_display_links` is provided.

            return []

然后使用這個答案,您可以自定義任何列。


第二種解決方案:

自己處理更改視圖

在您的管理課程中:


@admin.register(Category)

class CategoryAdmin(admin.ModelAdmin):

   #... same things as you have


   def change_view(self, request, object_id, form_url="", extra_context=None):

       #Now, you can do pretty much whatever: it's a function based view!

我推薦第一個,因為我相信默認管理員change_view總是有用的。


查看完整回答
反對 回復 2022-06-28
  • 1 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號