Limit user based field selection

I want the form to display only the current user accounts in ChoiceField. I tried the following, but that will not work.

Edit: Sorry, I forgot to mention "if kwargs", which I added because TransForm () does not show any fields. I think this is wrong, but I do not know another way.

views.py:

def in(request, account): if request.method == 'POST': form = TransForm(request.user, data=request.POST) if form.is_valid(): ... else: form = TransForm() context = { 'TranForm': form, } return render_to_response( 'cashflow/in.html', context, context_instance = RequestContext(request), ) 

forms.py:

 class TransForm(ModelForm): class Meta: model = Trans def __init__(self, *args, **kwargs): super(TransForm, self).__init__(*args, **kwargs) if kwargs: self.fields['account'].queryset = Account.objects.filter(user=args[0]) 
+4
source share
2 answers

You also need to properly initialize the form when the request is not submitted:

 if request.method == 'POST': form = TransForm(user=request.user, data=request.POST) if form.is_valid(): ... else: form = TransForm(user=request.user) ... 

and furthermore, I recommend removing the new argument when calling the superclass constructor:

 class TransForm(ModelForm): class Meta: model = Trans def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(TransForm, self).__init__(*args, **kwargs) self.fields['account'].queryset = Account.objects.filter(user=user) 
+4
source

Try this in forms.py:

 class TransForm(ModelForm): class Meta: model = Trans def __ini__(self, user, *args, **kwargs): super(TransForm, self).__init__(*args, **kwargs) qs = Account.objects.filter(user=user) self.fields['account'] = ModelChoiceField(queryset=qs) 

I assume that you imported forms as from django.forms import * .

I'm not sure what exactly is causing your problem, but I suspect two things (maybe both):

  • You call the constructor of the super class with an unexpected argument (by the user).
  • The selection on ModelChoiceField is determined when the field constructor runs, which runs as part of the superclass constructor, in which case you set up a set of queries after this fact does not affect the selection.
+1
source

All Articles