Пользовательский набор запросов django-formset

Я использую https://django-formset.fly.dev / библиотека, версия 1.7.6. Я пытаюсь установить пользовательский набор запросов для ModelChoiceField, но у меня возникают проблемы с фильтрацией набора запросов на основе объекта запроса. В частности, я хочу отфильтровать и настроить набор запросов так, чтобы он включал только определенные InRGPItem объекты.

Не могли бы вы посоветовать, как правильно настроить пользовательский набор запросов для ModelChoiceField в этом контексте?

forms.py

# django libraries
from django.forms.widgets import HiddenInput
from django.forms.models import ModelChoiceField, ModelForm

# django-formset libraries
from formset.collection import FormCollection
from formset.widgets import Selectize, DateInput, TextInput, Button
from formset.renderers.bootstrap import FormRenderer as BootstrapFormRenderer

# project models
from rgp_entry_app.models import OutRGPEntry, OutRGPItem, InRGPItem


class OutRGPItemForm(ModelForm):

    in_rgp_item = ModelChoiceField(
        label="In RGP Item",
        queryset=InRGPItem.objects.none(),  # Using direct empty queryset instead
        empty_label="Select",
        # to_field_name="guid",
        # widget=Selectize(
        #     search_lookup="name__icontains",
        # ),
    )
    class Meta:
        model = OutRGPItem
        fields = ['in_rgp_item', 'sent_qty', 'note']
        widgets = {
            'note': Textarea(attrs={'rows': 1}),
        }

class OutRGPItemCollection(FormCollection):
    outrgpitem = OutRGPItemForm()         # ✅ repeatable formset items
    related_field = 'out_rgp_entry'
    legend = "Out RGP Items"
    min_siblings = 1
    is_sortable = True
    ignore_marked_for_removal = True

class OutRGPEntryCollection(FormCollection):
    outrgpentry = OutRGPEntryForm()
    outrgpitem_set = OutRGPItemCollection()
    legend = "Out RGP Entry"
    default_renderer = BootstrapFormRenderer(
        form_css_classes='row',
        field_css_classes={
            # '*': 'mb-2 col-4',
            'chalan_no': 'col-sm-4',
            'chalan_date': 'col-sm-4',
            'rgp_date': 'col-sm-4',
            'in_rgp_item': 'mb-2 col-sm-4',
            'sent_qty': 'mb-2 col-sm-4',
            'note': 'mb-2 col-sm-4',
        },
    )

views.py

# django libraries import
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpRequest, HttpResponseRedirect, JsonResponse, HttpResponse, HttpResponseBadRequest

# third-party libraries
from formset.views import FormCollectionView, FormView, EditCollectionView, FormViewMixin

# project forms import
from rgp_entry_app.forms import OutRGPEntryCollection

# project models import
from rgp_entry_app.models import RGPCustomer, InRGPEntry, InRGPItem


class OutRGPEntryCreateView(EditCollectionView):
    pk_url_kwarg = 'in_rgp_entry_guid'
    model = InRGPEntry
    collection_class = OutRGPEntryCollection
    template_name = 'admin_panel/rgp_entry/out_rgp_entry/out_entry_form.html'
    success_url = reverse_lazy("rgp_entry_app:rgp_entry_view")

    def get_object(self, queryset=None):
        if queryset is None:
            queryset = self.get_queryset()
        guid = self.kwargs.get(self.pk_url_kwarg)
        if guid is not None:
            queryset = queryset.filter(guid=guid)
        obj = get_object_or_404(queryset)
        return obj

    def get_initial(self):
        print(f"START:get_initial")
        initial = super().get_initial()
        print(f"BEFORE:initial: {initial}")
        in_rgp_entry = self.get_object()
        print(f"in_rgp_entry: {in_rgp_entry}")
        
        # Set initial values for the main form
        initial['outrgpentry'] = {
            'in_rgp_entry': in_rgp_entry.id,
        }
        
        # Set initial values for the items collection
        initial['outrgpitem_set'] = []
        for item in in_rgp_entry.inrgpitem_set.all():
            initial['outrgpitem_set'].append({
                'outrgpitem' : {
                    'in_rgp_item': item.id,  # Use item.id instead of item object
                    'sent_qty': item.qty,  # Set initial sent_qty to the original qty
                }
            })
            
        print(f"AFTER:initial: {initial}")
        print(f"END:get_initial")
        return initial

    def get_context_data(self, **kwargs):
        print(f"START:get_context_data")
        context = super().get_context_data(**kwargs)
        context["rgp_entry_nav"] = "active"
        context["in_rgp_entry"] = self.get_object()  # Add InRGPEntry object to context
        print(f"END:get_context_data")
        return context

models.py

Вернуться на верх