What's the best way to serialize a ModelForm object in Django?

I am using Django and Google Web Toolkit (GWT) for my current project. I would like to pass an instance of ModelForm to GWT via the Http response so that I can "slice" it and display it however I please. My goal is to keep the form in sync with the changes in the models.py file, while still increasing control over the form's appearance. However, the serialization django classes, serializers and simplejson cannot serialize the ModelForm. Also can't cPickle. What are my alternatives?

+1


source to share


2 answers


If you are using pure Django, you must pass the form to your template and then call individual fields on the form for more accurate rendering, rather than using ModelForm.to_table. You can use the following to iterate over each field and display it exactly the way you want:

{% for field in form.fields %}
    <div class="form-field">{{ field }}</div>
{% endfor %}

      



It also gives you the ability to do conditional checks using {% if%} blocks inside the loop if you want to exclude certain fields.

+1


source


If your problem is to serialize ModelForm to json, just write your own subclass of simplejson serializer.



0


source







All Articles