django - 尽管设置良好,但 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')
你有什么线索吗?
解决方案
推荐阅读
- jinja2 - 如何使用 Jinja for 循环连接字符串?
- node.js - Windows:安装节点,然后在相同的 .ps1 脚本中 npm 包得到错误“npm”无法识别
- docker - 在 Docker Swarm 主机网络中发布端口
- java - 在 JavaFX 中为多个 TextField 编写 MouseClicked 事件的最简单方法
- ruby-on-rails - 通过向后读取来反转 Ruby 中的字符串
- php - 如何在 preg_match 中添加可选的验证模式?
- java - 使用 Apache POI 刷新数据透视表时,getPivotCacheDefinition 返回空值
- botframework - 如何在 botframework 中获取信使的页面访问令牌
- c# - 在带有 Razor 页面的 ASP.NET Core MVC 中使用 Handler 设置 Kendo UI Grid DataSource 读取属性
- ruby-on-rails - 如何更新rails中的关联记录