tags:

views:

763

answers:

3

thanks guys.i managed to complete it.million thanks again specially for DAVID,WM-EDDIE and S.LOTT.also STACKOVERFLOW

The solution:

                **model = Contact()
                model.contact_owner = request.user
                model.contact_name = row[1]
                model.contact_mobile_no = row[2]
                model.select_group = row[3]
                model.save()**

my user.py

def import_contact(request):
 if request.method == 'POST':
    form = UploadContactForm(request.POST, request.FILES)
    if form.is_valid():
            csvfile = request.FILES['file']
            print csvfile

            csvfile.read()
                testReader = csv.reader(csvfile,delimiter=' ', quotechar='|')

            **#what code should i write here to store data in mysql**


            for row in testReader:
                    print "|".join(row)
    return HttpResponseRedirect('/admin')


else:
    form = UploadContactForm()

vars = RequestContext(request, { 'form': form })
return render_to_response('admin/import_contact.html', vars)

the data in csv file:

abubakar,rooney,0178222123,student

abubakar,ronaldo,0183886789,student

abubakar,kaka,0197887898,bola

appreciated any suggestion.and hopefully can show me some coding example coz i'm still beginner in this language

my models.py:

class Contact(models.Model):

contact_owner = models.ForeignKey(User, related_name="contacts")
contact_name = models.CharField(max_length=20)
contact_mobile_no = models.CharField(max_length=20)
select_group = models.CharField(max_length=20, null=True)

def __unicode__(self):
   return "contact {contact_owner=%s, contact_name=%s, contact_mobile_no=%s, select_group=%s}" % (self.contact_owner, self.contact_name, self.contact_mobile_no, self.select_group)
A: 

To tokenize a comma separated string:

>>> a = 'abubakar,rooney,0178222123,student abubakar,rooneyzzz,0178222164'
>>> b = a.split(',')
>>> print b
['abubakar', 'rooney', '0178222123', 'student abubakar', 'rooneyzzz', '0178222164']

See @wm_eddie's answer for how to create a new entry in your db.

David
Splitting on ',' works only until you have a comma in a cell. That's why there's the csv module. It should properly handle commas inside "quotes" and properly escaping the quote character. One really has no idea how awesome it is to have a csv module in the standard library until you have to make one yourself.
wm_eddie
david,a = 'abubakar,rooney,0178222123,student abubakar,rooneyzzz,0178222164' you use is already declare by you.how i want to determine 'a' from the file as the file is uploaded.for example a = csv.reader(csvfile) or what,to automatically read 'abubakar,rooney,0178222123,student abubakar,rooneyzzz,0178222164'
s_atfi
A: 

Python's manuals are pretty bad. You are "supposed" to infer that because they use the string.join() that row works like an list. So pretty much it parses the CSV file into a list of lists. It takes care of all the nasty quoting, and escaping for you.

You use it just like you would use an array/list

for row in testReader:
    model = YourModel()
    model.property_a = row[0]
    model.property_b = row[1]
    model.save()

There's also a DictReader which allows you to write a more readable:

for row in testReader:
    model = YourModel()
    model.property_a = row["prop_a"]
    model.property_b = row["prop_b"]
    model.save()
wm_eddie
"infer"? I don't think so. http://docs.python.org/library/csv.html#csv.csvreader.next says "Return the next row of the reader’s iterable object as a list" It looks pretty clear to me.
S.Lott
The docs do say it clearly, but the "".join(row) is their way of illustrating that it's a list. A pretty bad illustration if you ask me.
wm_eddie
A: 

This is approximately what we do.

header = 'contact_owner', 'contact_name', 'contact_mobile_number', 'select_group'
rdr= csv.reader(request.FILES['file'])
for row in rdr:
    data = zip( header, row )
    owner, created = User.get_or_create( data['contact_owner']
    data['contact_owner']= owner
    contact, created = Contact.get_or_create( **data )
    logger.info( "Created %r", contact )

http://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create-kwargs

Your question says "tokenizer by comma". Your example data uses comma. But your csv.reader code shows spaces. Which is it?

S.Lott
it should be comma :P
s_atfi