У меня есть следующая форма:
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')
У вас есть какие-нибудь подсказки?