[Fixed]-Django admin โ€“ add more controls to the field

1๐Ÿ‘

โœ…

Try this:

from django.contrib.auth import forms
import datetime

class AddDaysForm(forms.ModelForm):
    add_extra_days_to_subscription_expiry = forms.IntegerField(required=False)

    class Meta:
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance')
        if instance:
            self.base_fields['add_extra_days_to_subscription_expiry'] = 0
        forms.ModelForm.__init__(self, *args, **kwargs)

class SubscriptionAdmin(admin.ModelAdmin)
    form = AddDaysForm
    list_display = ('id', 'domain', 'domain_created',)

    def save_model(self, request, obj, form, change):
        if form.cleaned_data['add_extra_days_to_subscription_expiry'] != 0:
            obj.subscription_expire = obj.subscription_expire + datetime.timedelta(days=form.cleaned_data['add_extra_days_to_subscription_expiry'])
            obj.save()

With this solution, you simply enter a number and then hit save via the admin, and it will add it for you. When the form reloads, it will reset back to 0 so that you can enter a new value. Note, that it also accounts for when the form is saved from the default โ€˜0โ€™ value.

๐Ÿ‘คdeadlock

Leave a comment