[Fixed]-Changing a date into a checkbox in Django

0👍

Try with initial:

https://docs.djangoproject.com/en/1.8/ref/forms/api/#dynamic-initial-values

In your view check the state of inactive_date field and then pass the result to the form via initial argument.

Hope it can help.

1👍

Create a new widget with the desired behavior. The default CheckboxInput widget (tested in django 3.2) properly checks or unchecks the checkbox based on if the field is a datetime or None. Then, you just override the response returned from user input:

from django.forms.widgets import CheckboxInput
from django.utils import timezone


class DateTimeCheckboxInput(CheckboxInput):
    def value_from_datadict(self, data, files, name):
        # cast the boolean returned to a timestamp or None
        value = super().value_from_datadict(data, files, name)
        return timezone.now() if value else None

Then, you can use this widget in any django model form

class MyCustomerForm(ModelForm):
    class Meta:
        model = MyCustomer
        fields = ['inactive_checkbox']
        widgets = {
            "inactive_checkbox": widgets.DateTimeCheckboxInput,
        }

0👍

I wanted to post my new form based on jorlugaqui’s answer as a comment, but comments are very limited in terms of formatting and length.

So here’s my new form and view based on jorlugaqui’s recommendation:

New form:

class MyCustomerForm(ModelForm):
    inactive_checkbox = forms.BooleanField(required=False, label="Inactive")

    class Meta:
        model = MyCustomer
        fields = ['customer_id','customer_name','customer_phone']

New view:

def customer_detail(request):
    id = request.GET.get('id')
    item = MyCustomer.objects.get(customer_id=id)

    if request.method == 'POST':
        form = MyCustomerForm(request.POST, instance=item, initial={'inactive_checkbox': item.inactive})
        if form.is_valid():
            inactive = request.POST.get('inactive_checkbox')
            modified_item = form.save(commit=False)
            if inactive:
                if modified_item.inactive == None:
                    modified_item.inactive = datetime.datetime.now().strftime("%Y-%m-%d")
            else:
                modified_item.inactive = None
            modified_item.save()
    else:
        form = MyCustomerForm(initial={'inactive_checkbox': item.inactive}, instance=item)
    return render(request, 'basic_detail.html', {'id': id, 'form': form})
👤Adron

Leave a comment