【问题标题】:Is there any widgets available for `DurationField` in Django?Django 中是否有可用于“DurationField”的小部件?
【发布时间】:2019-07-30 14:17:19
【问题描述】:

我即将为管理站点添加 DurationField 的小部件,并希望输入持续时间字段的小部件。

问题陈述

PromoCode类下面有DurationFieldduration。但在管理员中,它显示TextInput 作为输入。

class PromoCode(models.Model):
    """
    Promo Code model to maintain offers
    """
    code = models.CharField(_("Code"), max_length=60, help_text="Promo code")
    # Validations and constraints for promo code
    start_date = models.DateField(_("Start date"), null=True, blank=True, help_text="Start date of promo code offer")
    end_date = models.DateField(_("End date"), null=True, blank=True, help_text="End date of promo code offer")
    duration = models.DurationField(_("Duration"), null=True, blank=True, help_text="Validity period of promo code")
    ...
    ...

admin.py

class PromoCodeAdmin(admin.ModelAdmin):
    """
    Model admin for promocodes
    """
    list_display = ('code', 'description', 'start_date', 'end_date',)
    fields = (
    'code', 'description', 'discount', 'start_date', 'end_date', 'duration', 'sitewide_countdown', 'user_countdown',
    'coin_currencies', 'fiat_currencies',)

下图仅供参考,duration 字段不是人类可读格式。

预期行为

DurationField 的小部件添加到管理表单以使其易于阅读和编辑的最佳方式是什么?目前管理员很难添加持续时间。

【问题讨论】:

    标签: django django-admin django-widget


    【解决方案1】:

    您可以在管理员中使用@pre_save 并将持续时间转换为您想要的可读格式。

    【讨论】:

    • 其实我想要表单输入小部件。处理这个持续时间字段
    【解决方案2】:

    这似乎是你需要的:http://www.columbia.edu/~njn2118/journal/2015/10/30.html

    我只想补充一点,您需要在管理类中设置自定义表单。

    喜欢:

    from .forms import ModelFormWithDurationWidget
    
    class SnippetAdmin(admin.ModelAdmin):
        save_as = True
        prepopulated_fields = {'slug': ('name',)}
        form = ModelFormWithDurationWidget
        inlines = [
        SliderInline,
        ]
    

    【讨论】:

      猜你喜欢
      • 2011-10-21
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 2021-08-15
      相关资源
      最近更新 更多