简体   繁体   English

如何使用相关模型中的对象填充ModelForm中Field的初始值?

[英]How would I use the objects from a related Model to populate the initial value of a Field in a ModelForm?

My issue is with the 5th line below (the one with all of the question marks): 我的问题是下面的第五行(带有所有问号的那一行):

class EditProfileForm(forms.ModelForm):
    """ Base form used for fields that are always required """
    first_name = forms.CharField(label=_(u'First name'), max_length=30, required=False)
    last_name = forms.CharField(label=_(u'Last name'), max_length=30, required=False)
    language = forms.ModelMultipleChoiceField(label=_(u'Language'), queryset=Language.objects.all(), initial=VolunteerLanguage.objects.filter(volunter=??????????))
    categories = forms.ModelMultipleChoiceField(label=_(u'Categories'), queryset=TaskCategory.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False)

    def __init__(self, *args, **kw):
        super(EditProfileForm, self).__init__(*args, **kw)
        self.profile = super(EditProfileForm, self).save(True)
        # Put the first and last name at the top
        new_order = self.fields.keyOrder[:-3]
        new_order.insert(0, 'first_name')
        new_order.insert(1, 'last_name')
        new_order.insert(2, 'language')
        self.fields.keyOrder = new_order

    class Meta:
        model = get_profile_model()
        exclude = ['user', 'editions', 'tasks', 'signed_up', 'language']

    def save(self, force_insert=False, force_update=False, commit=True):
        profile = super(EditProfileForm, self).save(commit=commit)
        # Save first and last name
        VolunteerLanguage.objects.filter(volunteer=profile).delete()
        for lang in self.cleaned_data['language']:
            languages = VolunteerLanguage(volunteer=profile, language=lang)
            languages.save()
        user = profile.user
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()

        return profile

The problem is that I cannot retrieve the objects from VolunteerLanguage (link table) as I need to pass a Volunteer object to it in order to filter it. 问题是我无法从VolunteerLanguage(链接表)中检索对象,因为我需要将Volunteer对象传递给它以对其进行过滤。 I can do that in the save method, but not on line 5 我可以在save方法中做到这一点,但不能在第5行上做到这一点

If you want to pass an additional parameter to your form and use that value to setup a field you can do something like this: 如果要向表单传递其他参数并使用该值设置字段,可以执行以下操作:

class EditProfileForm(forms.ModelForm):

    def __init__(self, initial_volunteer, *args, **kwargs):
            super(EditProfileForm, self).__init__(*args, **kwargs)
            self.fields['language'] = forms.ModelMultipleChoiceField(
            label=_(u'Language'), 
            queryset=Language.objects.all(),
            # now you have the value you passed to use here
            initial=VolunteerLanguage.objects.filter(volunteer=initial_volunteer)
            )

If the self.profile already in your __init__ is the one you want to use you can create your field in the __init__ the same way as my example just don't pass a new value and use your self.profile instead. 如果__init__已经存在self.profile ,那么您可以像我的示例一样在__init__创建字段,只是不传递新值,而是使用self.profile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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