0

Is there a way I can access the form that caused a post_save?

The use case is that I have a field (a checkbox) that isn't attached to a particular model, but it's an extra field in the form itself.

I want to know whether the field was checked or unchecked when the form got saved and the model stored, and imho the post_save signal is a good place to put the logic that should process that extra field.

I'm also open to suggestions where else I could put that piece of code.

alexandernst
  • 14,352
  • 22
  • 97
  • 197

1 Answers1

1

post_save won't know anything about any form that might have caused the model change.

If you want to access that checkbox value you need to do it in the form class itself. I would probably override the clean() method of the form, and check for the checkbox value in cleaned_data['checkbox_field'] there, and then do whatever you need to with it.

Chris
  • 366
  • 3
  • 11
  • The `clean` method will be called way too soon for my purpose. I need to do my logic after the model has been successfully saved. – alexandernst Feb 16 '18 at 01:28
  • Then you probably want to override the `save()` method on the form and put the logic there. Assuming you are using a `ModelForm`. – Chris Feb 16 '18 at 01:31
  • But doing business logic in the `save()` method of the form feels quite ugly. – alexandernst Feb 16 '18 at 01:32
  • I guess without knowing what you are doing it's hard to suggest anything else. I think you basically have three ugly options: squirrel that checkbox value away somewhere for later use, access `request.POST` directly in your view, or do your stuff in the form class somewhere. Or rethink your approach altogether. – Chris Feb 16 '18 at 01:52