首页 > 解决方案 > 尽管设置良好,但 Django ModelChoiceField 初始值不起作用

问题描述

我有以下表格:

class UserUpdateForm(ModelForm):

    class Meta:
        model = User
        fields= '__all__'
        widgets = {
            'inscription_date': forms.DateInput(format=('%d-%m-%Y'),
                                                 attrs={'class': 'datepicker',
                                                        'placeholder': 'Select a date'})
        }

    def __init__(self, *args, **kwargs):
        super(UserUpdateForm, self).__init__(*args, **kwargs)
        current_user_id = User.objects.get(id=self.instance.id).id
        group_name = GroupName.objects.filter(
            usergroup__user__id=current_user_id).get().name
        current_location = User.objects.filter(id=self.instance.id).values(
            location=F('record__location__nom')).distinct().get()

        self.fields['location'] = forms.ModelChoiceField(
            queryset=Location.objects.all(), initial=current_location['location'])



    def get_form(self):
        form = super().get_form()
        return form

初始值不起作用。我检查了一下,里面的值current_location['location']是正确的。

我也试着写self.initial['location'] = current_location['location'],但还是不行。

这就是我实例化表单的方式:

@method_decorator(login_required, name='dispatch')
class UserUpdateView(LoginRequiredMixin, UpdateView):
    model = User
    form_class = UserUpdateForm
    template_name = 'dashboard/users/user_update_form.html'

    def get_success_url(self):
        messages.success(self.request, "The user %s was updated successfully" % (
            self.object.first_name))
        return reverse_lazy('dashboard:users')

你有什么线索吗?

标签: djangopython-3.xdjango-forms

解决方案


推荐阅读