Search code examples
pythondjangodatabasemodelduplicates

Duplicated insertion in database using django


I have the following model that i need to save :

def validate_pdf(value):
    if not value.name.endswith('.pdf'):
        raise ValidationError("O arquivo deve ser no formato PDF.")

class Documento(models.Model):
    titulo = models.CharField(max_length=200)
    autor = models.CharField(max_length=200)
    instituicao = models.CharField(max_length=200)
    arquivo_pdf = models.FileField(validators=[validate_pdf])
    tamanho = models.BigIntegerField(default=1) 

and that's my creationview:

class DocumentoCreateView(CreateView):
    model = Documento
    fields = (
        "titulo",
        "autor",
        "instituicao",
        "arquivo_pdf"
    )
    template_name = "documentos/documento_new.html"
    success_url = reverse_lazy("documento_new")

    def post(self, request, *args, **kwargs):
        super(DocumentoCreateView, self).post(request)
        form = DocumentoCreateForm(request.POST, request.FILES)
        print(form.errors)
        if form.is_valid():
            documento = form.save()
            #documento.save()
            path = f'/media/' + form.files['arquivo_pdf'].__str__()
            extracao_de_texo = TextExtractor(path)

and this one is the form that I use to create the model:

class  DocumentoCreateForm(forms.ModelForm):
    class Meta:
        model = Documento
        fields = [
            "titulo",
            "autor",
            "instituicao",
            "arquivo_pdf"
        ]

and my issue is that a model is saved even if the form.is_valid() is false, so it means that it is saved before the validation.

I was expecting that the model would be inserted only when i call the form.save() method. I don't know what could be this issue.


Solution

  • You need to remove the line

    super(DocumentoCreateView, self).post(request)