如何解决如何根据某些条件在Django管理员中更改某些类似字段的外观 1第一种方法:使用模型方法检查字段值 2第二种方法:使用管理器方法同时检查所有字段中的值
我想要什么
我有三个类型为DateField
的字段,如果该字段的值是特定日期,则我想更改其在管理员中的外观,而无需重复相同的方法来检查每个字段的值并进行更改它们的外观(干)。
我尝试过的事情
1。第一种方法:使用模型方法检查字段值
模型class Case(TimeStampedModel,models.Model):
fulfillment = models.DateField(default=date.today)
caducity = models.DateField(default=date.today)
prescription = models.DateField(default=date.today)
# With this approach I need to repeat this method to check the value for every field
def is_prescripted(self):
"""Check if one case is prescripted."""
if self.prescription == date.today():
return True
return False
管理员
from django.contrib import admin
from .models import Case
@admin.register(Case)
class CaseAdmin(admin.ModelAdmin):
list_display = (
"_fulfillment","_caducity","_prescription",)
# With this approach I need to repeat this method to change the appearance for every field
def _prescription(self,obj: Case) -> str:
"""Render a red badge alert in the admin for cases that are prescribed."""
date = formats.date_format(obj.prescription)
if obj.is_prescripted():
return create_badge(text=date)
return date
2。第二种方法:使用管理器方法同时检查所有字段中的值
模特经理class CaseManager(models.Manager):
def expired(self) -> "QuerySet[Case]":
"""Get all fulfilled,caducated and prescribed cases."""
return self.get_queryset().filter(
Q(fulfillment=get_today())
| Q(caducity=get_today())
| Q(prescription=get_today())
)
模型
class Case(TimeStampedModel,models.Model):
# ... model fileds
objects = CaseManager()
管理员
from .models import Case
@admin.register(Case)
class CaseAdmin(admin.ModelAdmin):
list_display = (
"_fulfillment",obj: Case) -> str:
"""Render a red badge alert in the admin for cases that are prescribed."""
date = formats.date_format(obj.prescription)
for prescribed_case in Case.objects.prescribed():
if prescribed_case == obj:
return create_badge(text=date)
return date
辅助功能
此功能用于在管理员中为符合条件的日期打印红色的包。
from django.utils.html import format_html
def create_badge(
text: str = "",bg_color: str = "tomato",color: str = "white",padding: str = "2"
) -> str:
"""Create a css badge style for some text."""
badge = (
f"<span style='background-color: {bg_color};"
f"color: {color}; padding: {padding}px;"
"white-space: nowrap;'"
f">{text}</span>"
)
return f"{format_html(badge)}"
问题
-
第一种方法:第一种方法的问题是,我需要创建三个相同的模型和admin方法来检查每个字段的值并更改它们在admin中的外观。
-
第二种方法:通过这种方法,我解决了重复三种模型方法以检查每个字段的值的问题,但是在管理员中,我需要将方法管理器抛出的所有值与方法管理器的值进行比较。效率低下的每个领域的模型实例。而且仍然存在更改管理员中每个字段的外观的问题,就像第一种方法一样,我应该为每个字段重复相同的方法以更改其外观。
解决方法
也许是第三种方法:为日期字段覆盖/替换admindatewidget。
对于django以admin形式显示的每个字段,都使用一个小部件。 对于日期字段类型字段,使用了AdminDateWiget(站点包\ django \ contrib \ admin \ AdminDateWiget),它扩展了另一个小部件:
class DateInput(DateTimeBaseInput):
format_key = 'DATE_INPUT_FORMATS'
template_name = 'django/forms/widgets/date.html'
如您所见,默认模板是date.html:
<input type="{{ widget.type }}" name="{{ widget.name }}"{% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %}{% include "django/forms/widgets/attrs.html" %}>
好消息,您可以更改meta并替换特定模型的模板。
两个步骤:
1st:您需要创建一个新的html。我复制粘贴date.html并添加逻辑以比较日期值。
spedate.html:
{% now "Y-m-d" as current_time %}
{% if widget.value == current_time %}
<input type="{{ widget.type }}" class='my css' name="{{ widget.name }}"{% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %}{% include "django/forms/widgets/attrs.html" %}>
{% else %}
<input type="{{ widget.type }}" name="{{ widget.name }}"{% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %}{% include "django/forms/widgets/attrs.html" %}>
{% endif %}
2nd:链接新模板
在admin.py中创建一个新类并阅读文档
admin.py
class CustomerAdmin(admin.ModelAdmin):
template_name = "app_name/.../spedate.html"
formfield_overrides = {
models.DateField: { 'widget': AdminDateWidget },}
admin.site.register(Case,CustomerAdmin)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。