【问题标题】:Django 1.11 Template not rendering MultipleChoiceField correctly which is working with django 1.4Django 1.11 模板未正确呈现与 django 1.4 一起使用的 MultipleChoiceField
【发布时间】:2017-04-21 07:38:30
【问题描述】:

我正在尝试将现有应用程序从版本 1.4 升级到 1.11。 我有一个问题,MultipleChoiceField 被存储在数据库中,但模板没有将它们呈现为被检查。

models.py

class TestModel(models.Model):
    test = models.CharField(blank=True, max_length=200)

forms.py

from django import forms
from django.forms import ModelForm
from app.models import TestModel
CHOICES = (
    ('1', 'Select All'),
    ('a', 'choice 1'),
    ('k', 'choice 2'),
)
class TestForm(ModelForm):
    test = forms.MultipleChoiceField(choices=CHOICES, required=False, widget=forms.CheckboxSelectMultiple()
    )
    class Meta:
        model = TestModel
        fields = '__all__' 

form1 = TestForm(data={'test': ['a','k']})

当我使用 manage.py shell 运行它时,我得到了正确的 HTML 输出

打印表格1

<tr>
<th><label>Test:</label></th>
<td>
<ul id="id_test">
    <li>
    <label for="id_test_0"><input type="checkbox" name="test" value="1" id="id_test_0" onclick="selectAll(this);" />Select All</label>
    </li>
    <li>
    <label for="id_test_1"><input type="checkbox" name="test" value="a" checked id="id_test_1" onclick="selectAll(this);" />choice 1</label>
    </li>
    <li>
    <label for="id_test_2"><input type="checkbox" name="test" value="k" checked id="id_test_2" onclick="selectAll(this);" />choice 2</label>
    </li>
</ul>
</td>
</tr>   

在代码中可以看到有checked属性。

模板

<div id="Scrolldrive2">{{form1.test}}</div> 

选定的复选框不会在 UI 上呈现。

【问题讨论】:

    标签: django-forms django-1.11


    【解决方案1】:

    问题是由于模型返回的初始数据是字符串类型

    例如。 form1 = TestForm(initial={'test': u"[u'a', u'k']"})

    Django 1.4 可以在内部将数据转换为列表,这在 1.11 中没有发生。已将初始数据转换为列表,现在可以正常工作了。

    工作 sn-p 将“测试”字段数据呈现为列表类型而不是 forms.py 中的字符串类型

    import json
    def jsonify(data):
        return json.loads(data.replace("u'", "'").replace("'", '"'))
        #output is [u'a', u'k']  
    
    
    class TestForm(ModelForm):
        test = forms.MultipleChoiceField(choices=CHOICES, required=False, 
               widget=forms.CheckboxSelectMultiple())
        class Meta:
            model = TestModel
            fields = '__all__' 
        def __init__(self, *args, **kwargs):
            super(TestForm, self).__init__(*args, **kwargs)
            if self.instance:
                obj_data = self.instance.__dict__ 
                self.initial['test'] = jsonify(obj_data['test'])  
    

    【讨论】:

    • 我正在将 django 1.8 升级到 1.11,同样的事情让我抓狂。这节省了我重构数据和/或进行更糟糕的黑客攻击的时间。有它的形式是恰到好处的水平!谢谢!
    猜你喜欢
    • 2015-04-01
    • 2020-09-06
    • 2012-04-26
    • 2015-08-22
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 2019-10-27
    • 2018-04-11
    相关资源
    最近更新 更多