mercredi 13 décembre 2017

Get the change log for custom fields in Django admin

I have added two custom fields (Checkboxes) in a form under Django admin. These values are not fetching data from model, but I am fetching data from a micro service to show these checkboxes as checked/unchecked conditionally. Below is the sample code:

class CustomFieldForm(ModelForm):
    first_custom_field = forms.BooleanField(
        label=_("First custom field"),
        widget=forms.CheckboxInput,
        required=False
    )

    second_custom_field = forms.BooleanField(
        label=_("Second custom field"),
        widget=forms.CheckboxInput,
        required=False
    )

    def __init__(self, *args, **kwargs):
        super(CustomFieldForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.user_id:
            if get_first_custom_field(self.instance.user.id):
             self.fields['first_custom_field'].widget.attrs['checked'] = 'checked'

            if get_second_custom_field(self.instance.user.id):
            self.fields['second_custom_field'].widget.attrs['checked'] = 'checked'

Now the problem am facing is that every time, I call save_model method, and if these fields are checked, then these are logged in history every time although I haven't updated any of these. Here is the sample code for save_model

   def save_model(self, request, obj, form, change):
    super(ProfileAdmin, self).save_model(request, obj, form, change)

    update_custom_field(form.cleaned_data['first_custom_field'], obj.user)

    update_custom_field(form.cleaned_data['second_custom_field'], obj.user)

After exploring the Django code, I came to know that Django form caches the initial field values and then compare these with submitted field values to know the change. But in my case, I am updating the form fields under __init__ method, based on data fetched from my micro service, so django form always caches my fields as unchecked.

And every time I submit the form, and if these checkboxes are checked, then django always consider these values as changed, resulting duplicate logs for these custom fields.

Kindly suggest how can I fix this problem of duplicate logs?




Aucun commentaire:

Enregistrer un commentaire