Skip to content

Commit

Permalink
feat: add instance for model form
Browse files Browse the repository at this point in the history
  • Loading branch information
amaury.lerouxdupeyron committed Sep 10, 2024
1 parent 8698366 commit d6d9f40
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions admin_action_tools/admin/form_tool.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import functools
from importlib import import_module
from typing import Callable, Dict
from typing import Callable, Dict, Optional, Type

from django import forms
from django.contrib.admin import helpers
Expand Down Expand Up @@ -80,11 +80,11 @@ def run_form_tool(
if step == ToolAction.BACK:
# cancel ask, revert to previous form
data = tool_chain.rollback()
form_instance = form(data)
form_instance = self.__get_instance(form, data=data, instance=queryset_or_object)
# First called by `Go` which would not have tool_name in params
elif step == ToolAction.CONFIRMED:
# form is filled
form_instance = form(request.POST)
form_instance = self.__get_instance(form, data=request.POST, instance=queryset_or_object)
if form_instance.is_valid():
metadata = self.__get_metadata(form)
tool_chain.set_tool(tool_name, form_instance.data, metadata=metadata)
Expand All @@ -93,14 +93,22 @@ def run_form_tool(
# forward to next
return func(self, request, queryset_or_object)
else:
form_instance = form()
form_instance = self.__get_instance(form, instance=queryset_or_object)

queryset: QuerySet = self.to_queryset(request, queryset_or_object)
context = self.build_context(request, func, queryset, form_instance, tool_name, display_queryset)

# Display form
return self.render_action_form(request, context)

@staticmethod
def __get_instance(
form: Type[forms.BaseForm], data: Optional[dict] = None, instance: Optional[forms.BaseForm] = None
) -> forms.BaseForm:
if isinstance(form, forms.ModelForm):
return form(data, instance=instance)
return form(data)


def add_form_to_action(form: Form, display_queryset=True):
"""
Expand Down

0 comments on commit d6d9f40

Please sign in to comment.