如何根据某些条件在Django管理员中更改某些类似字段的外观 1第一种方法:使用模型方法检查字段值 2第二种方法:使用管理器方法同时检查所有字段中的值

如何解决如何根据某些条件在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)}"

问题

  1. 第一种方法:第一种方法的问题是,我需要创建三个相同的模型和admin方法来检查每个字段的值并更改它们在admin中的外观。

  2. 第二种方法:通过这种方法,我解决了重复三种模型方法以检查每个字段的值的问题,但是在管理员中,我需要将方法管理器抛出的所有值与方法管理器的值进行比较。效率低下的每个领域的模型实例。而且仍然存在更改管理员中每个字段的外观的问题,就像第一种方法一样,我应该为每个字段重复相同的方法以更改其外观。

解决方法

也许是第三种方法:为日期字段覆盖/替换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中创建一个新类并阅读文档

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_overrides

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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-