【问题标题】:Form initial data does not display in template表单初始数据不显示在模板中
【发布时间】: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


【解决方案1】:

request.POST 如果没有提交 POST 数据,则为空字典。必须使用request.POST or None,否则会被理解为“表单提交时所有字段为空”,不考虑初始化。

您也不应该在未提交的表单上调用is_valid()。

...
profile_form = MyForm(
    request.POST or None, instance=request.user.profile)
if request.method == 'POST' and profile_form.is_valid():
    ...

【讨论】:

  • 不幸的是,我得到了和上面一样的结果:(
  • 我认为您也不应该在未提交的表单上致电is_valid()。试试if request.method == "POST" and profile_form.is_valid():
  • 你是如何刷新你的页面的?可能只是您的浏览器没有更新字段以“保留您输入的数据”。如果您在新选项卡中打开页面,它应该可以防止这种行为。您还可以查看输入 value 属性的源代码。
  • 耶!就是这样,谢谢!我自己不会发现的:)
猜你喜欢
  • 2021-03-01
  • 1970-01-01
  • 2021-07-20
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 2017-12-13
  • 1970-01-01
相关资源
最近更新 更多