[Answer]-Django forms – how to filter number of available options in a form

1👍

Set the queryset attribute of the field somewhere. Because it depends on your user, it’s something you have to set during or after instantiating the form. For instance, here’s how to do it in the view:

def addfeed(request, user):
    user = request.user # why does this view take user as an arg and then reassign?
    page_title = "Add feed"
    categories = Category.objects.filter(user=request.user)
    if request.method == 'POST':
        form = FeedForm(request.POST)
        form.fields['category'].queryset = categories
        if form.is_valid():
            feed = form.save(commit=False)
            feed.user = request.user  
            feed.save()
            return HttpResponseRedirect("/user/" + user.username + "/manage")
    else:
        form = FeedForm()
        form.fields['category'].queryset = categories
    return render(request, "form_manage.html", {
        'page_title': page_title,
        'form': form,})

I removed the instance argument to your POST case’s form construction because that’s meant for passing in an existing Feed instance, not a categories queryset.

You could also do this in the form’s __init__ if you pass in the correct categories queryset.

0👍

I use javascript to do this. For example, you could pass a list of the relevant categories as extra context in your view then use javascript in your template to empty the pre-populated option field in the form and replace it with your extra context.

Leave a comment