Django ModelChoiceField初始值尽管设置正确,但仍无法正常工作

时间:2020-03-23 11:23:00

标签: django python-3.x django-forms

我的格式如下:

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')

您有任何线索吗?

0 个答案:

没有答案