Question

I have a Physical_therapy_order model and an Event model (an event has foreignkey to Physical_therapy_order). I have a view which allows a user to create a new event. It also has a form with 3 fields from the Physical_therapy_order model.

def PTEventCreateView(request, pt_pk):
    #get the pt order and create an a form for that order
    pt_order = get_object_or_404(Physical_therapy_order, pk=pt_pk)
    ptform = PT_schedule_form(instance=pt_order)

    if request.POST:
        eventform = PTEventForm(data=request.POST)
        ptform = PT_schedule_form(data=request.POST, instance=pt_order)

        if eventform.is_valid() and ptform.is_valid():
            #I do some checks here that compare data across the two forms.
            # if everything looks good i mark keep_saving=True so I can 
            # continue to save all the data provided in the two forms
            if keep_saving:
                ptform.save()
                eventform.save()
            #...send user to succss page

This works just FINE EXCEPT: my PTEvent model has a function attached to its post_save signal. This function pulls the event's related pt_order and makes some modifications to it. Now, if i save the eventform first then the changes from the signal don't happen. if i save the ptform first the ptform changes get discarded and the changes from the signal happen.

THIS IS IMPORTANT: The ptform is editing three entirely different fields than the post_save signal. So its not like they're modifying the same data, only the same model instance. I thought a form only saves the fields in its meta.fields attribute. Why would this be happening? Also, if i save the ptform first, then when eventsform is saved shouldn't the signal use the updated physical_therapy_order? I'm not sure if I'm even on the right track?

Was it helpful?

Solution

I think this is because of cached objects.

What I would suggest is

  • Save eventform first
  • Get new instance of pt_order either querying db or through saved instance of eventform
  • And then re-create form and save.

Sample code change:

# your code
if keep_saving:
    evt = eventform.save()
    # I'm not sure exact name of your field name for pt_order in Event model, change appropriately
    newptform = PT_schedule_form(data=request.POST, instance= evt.pt_order)
    newpt = newptform.save()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top