Inserting records into the database from a file

Asked

Viewed 68 times

-1

I’m trying to enter records into my database, specifically the model Participante from a file .csv, whose format is id, name, Cpf and email.

So far what I have in mine views.py is:

def presenca(request):

        form = UploadArquivo()
        
        if request.method == 'POST':
            formulario = UploadArquivo(request.POST, request.FILES)
            #data_evento = '-'.join(formulario.data['data'].split('/')[::-1])

            if formulario.is_valid():
                formulario.save(commit=False)
                formulario.save()

                arquivo = str(request.FILES.getlist('upload_csv')[0])           # pega o nome do arquivo
                                
            f = open('csv/' + arquivo.replace(' ', '_'), 'r')
                                
            for line in f:
                line = line.split(',')                          # separado por vírgula

                participante = Participante.objects.filter(cpf=line[2])  # pega o CPF da planilha
                                                
                if participante:        # se o cpf está preenchido
                    verifica = Participante.objects.filter(cpf=participante)   # verifica se o cpf da planilha coincide com algum do banco
                                                    
                    if not verifica:        # se nao coincide
                        cadastra = Participante.objects.create(participante__nome=line[0], participante__cpf=line[1], participante__email=line[2])
                        presenca = Participante(cadastra).save()        # salva os dados do participante no model Participante
                                                        
            f.close()

            return render(request, 'base.html', locals())

But you’re not saving it in the bank. If someone can give me a light, I would appreciate it. Thank you from now on for the attention!!

  • How is the model? More precisely Participante.

  • class Participante(models.Model):
 nome = models.CharField(max_length=100)
 cpf = models.CharField(max_length=13)
 email = models.EmailField()
 dt_criacao = models.DateTimeField(auto_now=True)


1 answer

0

updated the reply: Urls:

from django.urls import path
from .views import  CarregarView #, carrega ,
urlpatterns = [
   # path('carregar1/', carrega),
    path('carregar2/', CarregarView.as_view())

]

Forms:

from django import forms


class ContatoForm(forms.Form):
    objeto1 = forms.CharField(required=True)
    objeto2 = forms.CharField(required=True)

Model:

from django.db import models


class ExemploModel(models.Model):
    objeto1 = models.CharField(max_length=100)
    objeto2 = models.CharField(max_length=100)

View:

from django.shortcuts import render
from .models import ExemploModel
from django.views.generic.base import View
from django.shortcuts import redirect
from .forms import ContatoForm

#função
# def carrega(request): #Ao acessar a pagina carregara o arquivo e salvara no banco
#     #csv
#     for i in range(1,19):
#         carregar = ExemploModel(objeto1=f"informacao{i}", objeto2=f'dados2 {i}')
#         carregar.save()
#     return render(request, "carregar.html")



#class
class CarregarView(View):

    def get(self, request): # na requisição get, quando acessa ira adicionar os arquivis

        for i in range(1, 100):
            carregar = ExemploModel(objeto1=f"informacao111{i}", objeto2=f'dados111 {i}')
            carregar.save()
        return render(request, "carregar2.html")

    def post(self, request): # na requisição post a função ira carregar o csv
        form = ContatoForm(request.POST)

        if form.is_valid():
            #============================
            '''Seu Código'''
            # ============================
            for i in range(1,100):
                carregar = ExemploModel(objeto1=f"informacao222{i}", objeto2=f'dados222{i}')
                carregar.save()



            return redirect('index')

        return render(request, "carregar2.html", {'form': form})

htmls

example 1:

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>

example 2:

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form  method="post">
    {% csrf_token %}
    {{form}}
    </form>
</body>
</html>

Controlling both requests and both can enter data

  • Still not going to the database. :/

  • updated the reply, give a check.

  • I played the code just by adapting to the project names and got an error: Valueerror: The view emissao_certificado.views.presenca didn’t Return an Httpresponse Object. It returned None Instead. . :/

  • Instead of the Generic base view, try only with the load function, within it do a query searching the data if you don’t have the add query, here tested with Django 3.0

  • Hi, Jeferson. I have updates on the project. It shows the following error: Exception Value: &#xA;expected string or bytes-like object. This error is happening in the following code snippet of my views: cria_certificado = ParticipanteCertificado.objects.get_or_create(participante=participante, data=formulario.data) forms that was missing ask all the model fields Evento and then I made progress. Unfortunately, I’m stuck in this mistake now.

  • , by the expected message is a literal or bit.

  • That date=form.data that is with this impasse. I just don’t understand what it refers to exactly.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.