开发者

Django - populate a MultipleChoiceField via request.user.somechoice_set.all()

开发者 https://www.devze.com 2023-01-18 12:29 出处:网络
Is there a more efficient, or cleaner way to do the following? class SpamForm(ModelForm): some_choices = fields.MultipleChoiceField()

Is there a more efficient, or cleaner way to do the following?

class SpamForm(ModelForm):
    some_choices = fields.MultipleChoiceField()

    def __init__(self, *args, **kwargs):
        super(SpamForm, self).__init__(*args, **kwargs)
        self.fields['some_choices'].choices = [[choice.pk, choice.description] for choice in self.instance.user.somechoice_set.all()]

    class Meta:
        model = Spam

This is to populate the new form with choices that pertain to the current request.user (which is set on the instance that's passed into the form). Is t开发者_如何学Gohere a better way?


Use a ModelMultipleChoiceField in the form and set its queryset in __init__().

0

精彩评论

暂无评论...
验证码 换一张
取 消