I have a formset which has a field "Teams" which should be limited to the teams the current user belongs to.
def edit_scrapbook(request):
u=request.user
ScrapbookAjaxForm = modelformset_factory(Scrapbook, fields=
('description','status','team'))
choices=False
for t in u.team_set.all():
if choices:
choices=choices,(t.id,t.name)
else:
choices=choices,(t.id,t.name)
if request.method == 'POST':
formset = ScrapbookAjaxForm(request.POST,
queryset=Scrapbook.objects.filter(owner=u))
if formset.is_valid():
instances=formset.save(commit=False)
for i in instances:
i.owner=request.user
i.save()
formset.save_m2m()
return HttpResponseRedirect(reverse('scrapbooks.views.index'))
else:
formset = ScrapbookAjaxForm(queryset=Scrapbook.objects.filter(owner=u))
for form in forms:
for field in form:
if field.label == 'Team':
field.choices=choices
c=RequestContext(request)
return render_to_response('scrapbooks/ajax_edit.html',
{'fs':formset},context_instance=c)
This does not seem to affect the choices in the form at all. This is quite ugly and probably the result of looking at this problem for way too long. I have also tried using a custom formset but I can't seem to get the custom formset to accept the parameter.
How do I limit the choices for the Team field on my subselect in a formset based on the teams the user is in?