samedi 29 août 2015

Changing a date into a checkbox in Django

I have a customer table that has an id, name, telephone and a date where the customer was set to inactive (called 'inactive_date').

In my form, I only want a checkbox to appear. If there is a date, then the checkbox is set. If the date is empty, then the checkbox is not set.

The only way I can set the checkbox so far is by doing the following:

class MyCustomerForm(ModelForm):
     inactive_checkbox = forms.BooleanField(initial='checked')

I tried to use a clean or an init method to be able to set the checkbox based on a condition, but these attempts down below have been unsuccessful. My form always return the checkbox as unset regardless of the contents of the inactive_date.

class MyCustomerForm(ModelForm):
     inactive_checkbox = forms.BooleanField()
     def clean(self, *args, **kwargs):
         inactive_date = self.cleaned_data['inactive_date']
         if (inactive_date != None):
             self.fields['inactive_checkbox'] = 'checked'
         return self.cleaned_data

    def __init__(self, *args, **kwargs):
        super(myCustomerForm, self).__init__(*args, **kwargs)

        inactive_date = self.cleaned_data['inactive_date']
        if (inactive_date != None):
             self.fields['inactive_checkbox'] = 'checked'

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

Any idea what is wrong with my code or is there perhaps a better way to control my inactive_date through a checkbox?




Aucun commentaire:

Enregistrer un commentaire