简体   繁体   中英

django form exclude dynamic object from queryset

I try to exclude a object from the form queryset by rewriting the init. However i keep getting: TypeError: init () got an unexpected keyword argument 'name' now i am pretty new to init function so im not sure where i go wrong.

My form:

class TravelForm(forms.Form):
    """ travel form, own location excluded """

    travel = forms.ModelChoiceField(empty_label=None, queryset=Region.objects.all(), widget=forms.RadioSelect())

    def __init__(self, *args, **kwargs):
        super(TravelForm, self).__init__(*args, **kwargs)
        self.fields['travel'].queryset = Region.objects.exclude(**kwargs)

and in my view i use: where request.user.character.region.name is the name of the excluded region (i dont know how to exclude something by object, hence the name)

def travel(request):
    travel_form = TravelForm(name=request.user.character.region.name)

What am i doing wrong?

You should not replace all named args in a Form.__init__ . It is just simpler to declare a single new parameter:

class TravelForm(forms.Form):
    """ travel form, own location excluded """

    travel = forms.ModelChoiceField(empty_label=None, queryset=Region.objects.all(), widget=forms.RadioSelect())

    def __init__(self, *args, **kwargs):
        exclude_args = kwargs.pop('exclude', {})
        super(TravelForm, self).__init__(*args, **kwargs)
        self.fields['travel'].queryset = Region.objects.exclude(**exclude_args)

kwargs.pop() will remove exclude parameters from kwargs , if it is there. Otherwise, it will just return an empty dict {} .

Then you can instantiate your form with:

def travel(request):
    travel_form = TravelForm(exclude={'name': request.user.character.region.name})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM