using model form's validation for data import into django?

I have a django app and I need to import existing data from text files into the new database. Usually I would do something like this:

for i in lines():
    a = Mymodel()
    a.field1 = i[0]
    a.field2 = i[0]
    a.save()

this works fine, but no data validation takes place (except for the matching data type of the fields).

For inputting data via the webinterface, I wrote some ModelForm forms, which do all the data validation for me (in the clean() method). I do know how to populate and validate a form using request.POST as an input, but is it also possible to do the same on python shell? Can I somehow feed my original data into a dict and populate the form with these data?

Answers


yes,

in forms.py

class FormA(forms.ModelForm):
   class Meta:
      model = Mymodel
   def clean_field1(self):
      #logic here
      #return cleaned field1

in views.py

 def populate_dict(line):
     dict = {'field1': line[0], 'field2': line[2], ... }
     return dict

 def populate(request):
    for line in lines():
       initial = populate_dict(line)
       form = FormA(initial=initial)
       if form.is_valid():
         form.save()

Need Your Help

include/import separate AS3 file

actionscript-3 import include string-literals braces

I am trying to just include a .as file in my flash application. I'm sure it's not that difficult and I'm just getting something slightly wrong, but at the top of my code I always put: