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

假设我有一个 Category 的模型,并且它已经在 admin.py 中声明了。


我想使用 Django 模板覆盖做两件事。


在“添加类别+ ”附近的右侧添加一个按钮,该按钮仅在“类别列表”页面上可见,并将我带到另一个 URL。

覆盖 Category 对象的 URL,以便单击列表上的每个单独的类别会转到相应的 URL

# models.py


class 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)

# admin.py


@admin.register(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']

管理面板中的类别 在

http://img3.mukewang.com/62ba67300001c95919121071.jpg

这里,单击 Lifestyle 或 Travel 应该会将我带到两个外部 URL。

郎朗坤
浏览 201回答 1
1回答

德玛西亚99

第一个解决方案:手动覆盖list_display_links和更改您的字段这是一个两步的过程。首先,我们需要改变get_list_display_links默认行为。查看 django 的文档和源代码,您会发现它最终会使用list_display. 在您的管理课程中:@admin.register(Category)class CategoryAdmin(admin.ModelAdmin):&nbsp; &nbsp; list_display = ('name', 'language', 'created_at')&nbsp; &nbsp; list_filter = ('created_at', 'language')&nbsp; &nbsp; list_display_links = [] #< With this, you still can add up a link to your original admin&nbsp; &nbsp; search_fields = ('name',)&nbsp; &nbsp; date_hierarchy = 'created_at'&nbsp; &nbsp; ordering = ['-created_at']&nbsp; &nbsp; def get_list_display_links(self, request, list_display):&nbsp; &nbsp; &nbsp; &nbsp; """&nbsp; &nbsp; &nbsp; &nbsp; Return a sequence containing the fields to be displayed as links&nbsp; &nbsp; &nbsp; &nbsp; on the changelist. The list_display parameter is the list of fields&nbsp; &nbsp; &nbsp; &nbsp; returned by get_list_display().&nbsp; &nbsp; &nbsp; &nbsp; """&nbsp; &nbsp; &nbsp; &nbsp; if self.list_display_links or self.list_display_links is None or not list_display:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # We make sure you still add your admin's links if you explicitly declare `list_display_links`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return self.list_display_links&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # We return empty list instead of `list_display[:1]`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # if no `list_display_links` is provided.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return []然后使用这个答案,您可以自定义任何列。第二种解决方案:自己处理更改视图在您的管理课程中:@admin.register(Category)class CategoryAdmin(admin.ModelAdmin):&nbsp; &nbsp;#... same things as you have&nbsp; &nbsp;def change_view(self, request, object_id, form_url="", extra_context=None):&nbsp; &nbsp; &nbsp; &nbsp;#Now, you can do pretty much whatever: it's a function based view!我推荐第一个,因为我相信默认管理员change_view总是有用的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python