On Tue, Apr 19, 2016 at 01:12:13AM -0700, elcaiaimar wrote:
> Hello,
> 
> I' ve an application where I upload a CSV file and save all its rows in a 
> database. This is ok, but, at the moment, when I upload the file and it 
> exists some error on it, it saves all rows until the wrong row. What I want 
> to achieve is that if there is an error when I save, don't save anything. 
> Is there any way to do that?
> 
> if formularioarchivomedios.is_valid():
>             
>    reader = csv.DictReader(request.FILES['docfile'], delimiter=',') 
> 
>    for row in reader:
> 
>                 try:                
>                     titulo=row['titulo']
>                     url=row['url']
> 
>                     my_file = Medios(titulo=titulo, url=url)
>                     
>                     my_file.save()
> 
> 
> 
> Thank you in advance!

This is exactly the purpose of database transactions. All you need to
do is to wrap the block of code in transaction.atomic(), like this::

    from django.db import transaction

    [...]

    if formularioarchivomedios.is_valid():
        reader = csv.DictReader(request.FILES['docfile'], delimiter=',') 
        try:
            with transaction.atomic():
                for row in reader:
                    titulo = row['titulo']
                    url = row['url']

                    my_file = Medios(titulo=titulo, url=url)
                    
                    my_file.save()

        except WhateverErrorYouWantToHandle as e:
            handle_error(e)

Just make sure to handle the error outside of the atomic block; that
way, the transaction will be automatically rolled back if an error
does happen. If you handle the error inside the atomic block, Django
will think there was no error, and it will happily try to commit the
transaction as if everything was all right.

Good luck,

Michal

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/20160419084755.GC1129%40koniiiik.org.
For more options, visit https://groups.google.com/d/optout.

Attachment: signature.asc
Description: Digital signature

Reply via email to