Tuesday, February 24, 2015

Re: Read a csv file and save data in postgresql

Parsing a CSV file is not a particularly hard thing to do


You can change the example to read from the file in your model an instead of printing to the console, to store it in the database.

On Tue, Feb 24, 2015 at 8:53 PM, elcaiaimar <sepas91@gmail.com> wrote:
Hello,

I have a website and I need that users can introduce a csv file and save their data in a postgresql database. I can introduce a file and save it in media_dir and in the database (only the url). But what I want is save each row as a register in a table. I've searched some examples but I haven't found exactly this.

Is it possible to do? Has anyone done this before? I put my code to save the file in a database and in media below:

views
if 'formularioarchivo' in request.POST:
        formularioarchivo = UploadForm(request.POST, request.FILES)
        if formularioarchivo.is_valid():
          newdoc = Archivo(docfile = request.FILES['docfile'])
          newdoc.save(formularioarchivo)
          return HttpResponseRedirect('/edicioncuenca/')

        else:
        formularioarchivo = UploadForm()

models
class Archivo(models.Model):
    # gid_archivo = models.IntegerField(primary_key=True)
    docfile = models.FileField(upload_to='%Y/%m/%d')

forms
class UploadForm(forms.Form):
    docfile = forms.FileField(
        label='Selecciona un archivo'
    )

template
<form name="formulario" action="/edicioncuenca/" method="POST" enctype="multipart/form-data">
  {% csrf_token %}
  {{ formularioarchivo.as_p }}
  <input type="submit" name="formularioarchivo" value="Submit">
</form>

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3b4bb9f0-2539-4486-b47a-c782ff350e99%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CALn3ei3h%2BTKM8viUsXYfOjOFVJShcGmyWm-33%2BQBm3W%2B4Ve_XQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment