Devang Padhiyar
Devang Padhiyar

Reputation: 3707

Is there any widgets available for `DurationField` in Django?

I am about to add DurationField 's widget for admin site and want duration field's widget for input.

Problem statement

In below PromoCode class have DurationField namely duration. But in admin it shows TextInput as input.

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',)

Below image is just for reference, duration field is not in human readable format.

Reference image

Expected behaviour

What is the best way to add DurationField 's widget into admin form to make it easy to read and edit? Currently it is quite hard for admin to add time duration.

Upvotes: 6

Views: 2546

Answers (2)

LuisSolis
LuisSolis

Reputation: 538

This seems to be what you need: http://www.columbia.edu/~njn2118/journal/2015/10/30.html

I would just add that you need to set a custom form in your admin class.

like:

from .forms import ModelFormWithDurationWidget

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

Upvotes: 2

Solal
Solal

Reputation: 771

You could use @pre_save in the admin and transform duration to the readable format you want.

Upvotes: 1

Related Questions