Django - 将表单字段的初始值设置为当前数据库值的最简单方法,用于自定义 UserChangeForm?
Django - Easiest way to set initial value for form fields to the current database value, for custom UserChangeForm?
基本上我有一个使用我的用户模型的自定义 UserChangeForm 'Writer',我想将所有字段的默认值设置为数据库中的当前值(或请求用户的值)。最好的方法是什么?
我尝试在表单中设置默认值,但是在 forms.py
中无法访问请求对象
表格...
class writerChangeForm(UserChangeForm):
class Meta:
model = Writer
fields = ('username', 'email', 'first_name', 'last_name', 'country')
country = CountryField().formfield()
widgets = {'country': CountrySelectWidget()}
风景...
class ProfileView(generic.CreateView):
form_class = writerChangeForm
template_name = 'diary/profile.html'
感谢任何意见!
最好的方法是覆盖 get_initial()
方法。
class ProfileView(generic.CreateView):
form_class = writerChangeForm
template_name = 'diary/profile.html'
def get_initial(self):
# get_initial should return dict. They should be rendered in template.
writer = Writer.objects.get(pk=1) # first get data from database.
# dictionary key names should be same as they are in forms.
return {
'username': writer.username,
'email': writer.email,
'first_name': writer.first_name
}
基本上我有一个使用我的用户模型的自定义 UserChangeForm 'Writer',我想将所有字段的默认值设置为数据库中的当前值(或请求用户的值)。最好的方法是什么?
我尝试在表单中设置默认值,但是在 forms.py
中无法访问请求对象表格...
class writerChangeForm(UserChangeForm):
class Meta:
model = Writer
fields = ('username', 'email', 'first_name', 'last_name', 'country')
country = CountryField().formfield()
widgets = {'country': CountrySelectWidget()}
风景...
class ProfileView(generic.CreateView):
form_class = writerChangeForm
template_name = 'diary/profile.html'
感谢任何意见!
最好的方法是覆盖 get_initial()
方法。
class ProfileView(generic.CreateView):
form_class = writerChangeForm
template_name = 'diary/profile.html'
def get_initial(self):
# get_initial should return dict. They should be rendered in template.
writer = Writer.objects.get(pk=1) # first get data from database.
# dictionary key names should be same as they are in forms.
return {
'username': writer.username,
'email': writer.email,
'first_name': writer.first_name
}