Skip to main content
 首页 » 编程设计

python之表单初始数据不显示在模板中

2025年02月15日7落叶无声

我有一个表单,其中一些字段具有初始值。运行我的应用程序后,表单出现但其字段初始值不显示,只是一个空表单。

我在模板中放置了一个 {{ 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'} 

这是我的代码:

表单.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) 

View .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> 

请您参考如下方法:

request.POST 如果没有提交 POST 数据,则为空字典。您必须使用 request.POST 或 None,否则,它将被理解为“提交的每个字段为空白的表单”,并且不会考虑初始化。

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

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