I have a Django Form class defined likes this in Models
:
class AccountDetailsForm(forms.Form):
...
adminuser = forms.ModelChoiceField(queryset=User.objects.all())
This works OK, but it has some limitations I can't seem to work around:
(1) I would like to use a filter on the queryset, based on a variable accountid
passed to the form, like this:
User.objects.filter(account=accountid)
This can't work in the model because accountid
can't be passed as a variable, of course.
It follows that the queryset
must somehow be defined in the Views
, but as far as I can see it's a required field in the Form class.
(2) I would like to make the default choice of AccountDetailsForm
an object in the database, which I can select in the Views
like this:
User.objects.filter(account=accountid).filter(primary_user=1)
I've tried specifying the adminuser as a default value in the form, (which works with other standard form fields, like CharField
):
adminuser = User.objects.filter(account=accountid).filter(primary_user=1)
...
form = AccountDetailsForm({'adminuser': adminuser})
return render_to_response('accounts/edit/accountdetails.html',
{'form': form, 'account':account})
But no luck.
Should I be using something other than ModelChoiceField
given the flexibility I need here?
Thanks.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…