import os file_path = 'core/views.py' with open(file_path, 'r') as f: lines = f.readlines() new_lines = [] for line in lines: new_lines.append(line) if "call.status = 'completed';" in line: # Check next line to see if it's already there or not pass if "call.save()" in line and "if request.method == 'POST':" in "".join(new_lines[-50:]): # We want to insert after the call.save() inside complete_call # Let's check context context = "".join(new_lines[-10:]) if "call.status = 'completed';" in context: indent = line[:line.find("call.save()")] new_lines.append(f"{indent}if call_outcome == 'No Answer No Voice Mail':\n") new_lines.append(f"{indent} voter = call.voter\n") new_lines.append(f"{indent} # If no other pending calls, reset to 'to_be_called'\n") new_lines.append(f"{indent} if not ScheduledCall.objects.filter(voter=voter, status='pending').exists():\n") new_lines.append(f"{indent} Voter.objects.filter(pk=voter.pk).update(call_queue_status='to_be_called')\n") with open(file_path, 'w') as f: f.writelines(new_lines)