Django filter the queryset of ModelChoiceField - what did i do wrong? -
i know many questions exist same topic, confused on 1 point. intent show 2 modelchoicefields on form, not directly tie them game model.
i have following:
forms.py
class addgame(forms.modelform): won_lag = forms.choicefield(choices=[('1','home') , ('2', 'away') ]) home_team = forms.modelchoicefield(queryset=player.objects.all()) away_team = forms.modelchoicefield(queryset=player.objects.all()) class meta: model = game fields = ('match', 'match_sequence')
views.py
def game_add(request, match_id): game = game() try: match = match.objects.get(id=match_id) except match.doesnotexist: # have no object! pass game.match = match # form form = addgame(request.post or none, instance=game) form.fields['home_team'].queryset = player.objects.filter(team=match.home_team ) # handle post-back (new or existing; on success nav game list) if request.method == 'post': if form.is_valid(): form.save() # redirect list of games specified match return httpresponseredirect(reverse('nine.views.list_games')) ...
where confused when setting queryset filter. first tried:
form.home_team.queryset = player.objects.filter(team=match.home_team )
but got error
attributeerror @ /nine/games/new/1 'addgame' object has no attribute 'home_team' ...
so changed following: (after reading other posts)
form.fields['home_team'].queryset = player.objects.filter(team=match.home_team )
and works fine.
so question is, difference between 2 lines? why did second 1 work , not first? sure newbie (i one) question, baffled.
any appreciated.
django forms metaclasses
:
>>> type(addgame) <class 'django.forms.forms.declarativefieldsmetaclass'>
they create form instance according information given in definition. means, won't see when define addgame
form. when instantiate it, metaclass
return proper instance fields provided:
>>> type(addgame()) <class 'your_app.forms.addgame'>
so, instance, can access fields doing form.field
. in fact, bit more complicated that. there 2 types of fields can access. form['field']
you'll accessing boundfield
. used output , raw_input.
by doing form.fields['fields']
you'll accessing field python can understand. because if got input, there's validation , data conversion take places (in fact, fields used this, the general process of validation bit more complicated).
i hope might clear little issue may see, whole form's api big , complicated. simple end-users has lot of programming behind curtains :)
reading links provides clear doubts , improve knowledge useful topic , django in general.
good luck!
update: way, if want learn more python's metaclasses, this hell of answer topic.
Comments
Post a Comment