【发布时间】:2018-01-04 10:12:46
【问题描述】:
我有一个表单,其中包含一些具有初始值的字段。运行我的应用程序后,表单出现,但其字段初始值不显示,只是一个空表单。
我在模板中添加了{{ profile_form.initial }} 以确保表单具有初始数据。它返回一个带有初始数据的字典:
{'local_number': 'test-local-number', 'last_name': 'test-last-name', 'phone': 'test-phone', 'zip_code': 'test-zip-code', 'city': 'test-city', 'user': <User: testuser>, 'street': 'test-street', 'first_name': 'test-first-name'}
这是我的代码:
forms.py
class MyForm(forms.ModelForm):
initial_fields = ['first_name', 'last_name', 'phone', 'street',
'local_number', 'city', 'zip_code']
class Meta:
model = UserProfile
fields = ('first_name', 'last_name', 'phone', 'street',
'local_number', 'city', 'zip_code')
def __init__(self, *args, **kwargs):
self.instance = kwargs.pop('instance', None)
initial = kwargs.pop('initial', {})
for key in self.initial_fields:
if hasattr(self.instance, key):
initial[key] = initial.get(key) or getattr(self.instance, key)
kwargs['initial'] = initial
super(MyForm, self).__init__(*args, **kwargs)
views.py
def my_view(request):
context = {}
if request.user.is_authenticated():
profile_form = MyForm(
request.POST, instance=request.user.profile)
if profile_form.is_valid():
profile_form.save()
context.update({'profile_form': profile_form})
}
return render(request, 'template.html', context)
模板.html
<form class="animated-form" action="" method="POST">
{% csrf_token %}
{{ profile_form.initial }}
{{ profile_form.as_p }}
<div>
<div class="row">
<div class="col-lg-12 text-center">
<button type="submit">Submit</button>
</div>
</div>
</div>
</form>
【问题讨论】:
-
我不明白您表单的
__init__方法的用途。如果您将instance传递给模型表单,则该表单已经填充了初始实例。 -
哦,我明白了。你是对的 :) 删除这个“自定义初始化”后,没有任何变化,我会从我的代码中删除它。这不是问题解决方案,但仍然非常有用的评论:)
标签: python django forms django-templates