Home > Software design >  How to change a ModelChoiceField's query set before sending the form to user in a view?
How to change a ModelChoiceField's query set before sending the form to user in a view?

Time:12-16

I have this form:

class CategoryForm(forms.Form):
    category = forms.ModelChoiceField(queryset=Category.objects.filter(parent=None))

And a view:

def category_select(request, pk):
    if request.method == "POST":
        # ...
    else:
        form = CategoryForm()
        # I want to change category field's queryset here.

        return render(
            request,
            "ads/select-category.html",
            {
                "form": form,
            },
        )

In this view, I want to change queryset of category field in form (based on pk which it gets from the url as a parameter).

CodePudding user response:

form.fields['category'].queryset = Category.objects.filter(....)

def category_select(request, pk):
    if request.method == "POST":
        # ...
    else:
        form = CategoryForm()

        # Change the queryset of the category field
        form.fields['category'].queryset = Category.objects.filter(....)
        return render(
            request,
            "ads/select-category.html",
            {
                "form": form,
            },
        )
  • Related