I want to have a bound form from an object to use the is_valid method. The reason is because I have some old data that I want the users to correct according to the new validation rules. Then, I want to reuse the code of the clean methods in my form.
I ended up serializing my response:
from django.utils import simplejson
from django.core.serializers import serialize
(...)
fields_dict = simplejson.loads(serialize('json', [obj]))[0]['fields']
form = forms.MyForm(fields_dict)
if form.is_valid
This works but it doesn't seem very Djangish. Also, it seems as a common problem so I was looking for a better way of doing this.
According to the documentation, translating data from an unbound form to a bound form is not meant to happen: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method However, that would be the easiest solution for me.
So, a bound form has a RecordSource, a table or query to which the form is "tied" or "based". An unbound form does not have a RecordSource, that doesn't mean it can't contain data, but the programmer will have to bring that data in manually, where a bound form automatically is associated with some data.
What is a unbound form in Microsoft Access? Basically it is a form that is not bound to any database table or query. You can usually determine if a form (or a control on a form) is bound by looking at its record source property which will either be bound to a Table, Query or SQL String.
Bound control – associated with a field in an underlying table. Use bound controls to display, enter, and update values from fields in the database. Unbound control – does not have a data source. Use unbound controls to display pictures and static text.
There is Django's django.forms.models.model_to_dict
function that will convert your existing model instance into a dictionary of data suitable for binding to a ModelForm
.
This would probably be more efficient, and definitely more "Djangish", than serialising and unserialising the object.
And if you also create the form with the instance
keyword, it will know to update the existing record when saved.
So:
from django.forms.models import model_to_dict
...
fields_dict = model_to_dict(obj)
form = forms.MyForm(fields_dict, instance=obj)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With