假设我有一个 Category 模型,并且它已在 admin.py 中声明。
我想使用 Django 模板覆盖来做两件事。
- 在右侧“添加类别 +”附近添加一个按钮,该按钮仅在“类别列表”页面上可见,并将我带到另一个网址。
- 覆盖类别对象的网址,以便单击列表中的每个单独类别即可访问相应的网址
# 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']
最佳答案
第一个解决方案:
覆盖 list_display_links
并手动更改您的字段
这是一个两步过程。
首先,我们需要更改 get_list_display_links
默认行为。
查看 django 的 doc和 source您将意识到它将最终使用 list_display
中的第一项。
在您的管理类(class)中:
@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 []
然后使用 this answer ,您可以自定义任何列。
第二个解决方案:
自己处理更改 View
在您的管理类(class)中:
@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
总是有用的。
关于python - 使用模板覆盖更改 django 管理列表中的模型对象 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58427281/