I am using Django and the Google Web Toolkit (GWT) for my current project. I would like to pass a ModelForm instance to GWT via an Http response so that I can "chop" it up and render it as I please. My goal is to keep the form in sync with changes to my models.py file, yet increase control I have over the look of the form. However, the django classes for serialization, serializers and simplejson, cannot serialize a ModelForm. Neither can cPickle. What are my alternatives?
我正在使用Django和Google Web Toolkit(GWT)来完成我当前的项目。我想通过Http响应将ModelForm实例传递给GWT,这样我就可以“切断”它并按照我的喜好进行渲染。我的目标是使表单与我的models.py文件的更改保持同步,同时增加对表单外观的控制。但是,序列化,序列化器和simplejson的django类无法序列化ModelForm。也不能cPickle。我有什么选择?
2 个解决方案
#1
1
If you were using pure Django, you'd pass the form to your template, and could then call individual fields on the form for more precise rendering, rather than using ModelForm.to_table. You can use the following to iterate over each field and render it exactly how you want:
如果您使用的是纯Django,则可以将表单传递给模板,然后可以调用表单上的各个字段以获得更精确的渲染,而不是使用ModelForm.to_table。您可以使用以下内容迭代每个字段并按照您想要的方式呈现它:
{% for field in form.fields %}
<div class="form-field">{{ field }}</div>
{% endfor %}
This also affords you the ability to do conditional checks using {% if %} blocks inside the loop should you want to exclude certain fields.
如果您想要排除某些字段,这还使您能够使用循环内的{%if%}块进行条件检查。
#2
0
If your problem is just to serialze a ModelForm to json, just write your own simplejson serializer subclass.
如果您的问题只是将ModelForm序列化为json,那么只需编写自己的simplejson序列化器子类。
#1
1
If you were using pure Django, you'd pass the form to your template, and could then call individual fields on the form for more precise rendering, rather than using ModelForm.to_table. You can use the following to iterate over each field and render it exactly how you want:
如果您使用的是纯Django,则可以将表单传递给模板,然后可以调用表单上的各个字段以获得更精确的渲染,而不是使用ModelForm.to_table。您可以使用以下内容迭代每个字段并按照您想要的方式呈现它:
{% for field in form.fields %}
<div class="form-field">{{ field }}</div>
{% endfor %}
This also affords you the ability to do conditional checks using {% if %} blocks inside the loop should you want to exclude certain fields.
如果您想要排除某些字段,这还使您能够使用循环内的{%if%}块进行条件检查。
#2
0
If your problem is just to serialze a ModelForm to json, just write your own simplejson serializer subclass.
如果您的问题只是将ModelForm序列化为json,那么只需编写自己的simplejson序列化器子类。