Form in Django with more than one Model

Asked

Viewed 184 times

1

I’m new to programming and I’m trying to make a form using more than one Model in Django. I even managed to list the Fields of Forms.py, but when asked to save it only records the data of the first model. The error that gives is "NOT NULL Constraint failed: Geral_usuario.colaboradorId_id", which I believe is because I can not recover the id of the collaborator who was just registered. How could I be solving this?

I redid a "mini-code" to give an idea of how I’m doing.

py.models:

from django.db import models

class Colaborador(models.Model):
    nome = models.CharField()

class Usuario(models.Model):
    user = models.CharField(unique=True)
    senha = models.CharField()
    colaboradorId = models.OneToOneField('Colaborador', on_delete=models.CASCADE)

class Email(Contato):
    email = models.CharField()
    colaboradorId = models.ForeignKey('Colaborador', on_delete=models.CASCADE)

Forms.py:

from django.forms import ModelForm
from django import forms
from .models import Colaborador, Usuario, Email

class FormUsuario(ModelForm):
    class Meta:
        model = Usuario
        fields = ['user', 'senha']

class FormColaborador(ModelForm):
    class Meta:
        model = Colaborador
        fields = ['nome']

class FormEmail(ModelForm):
    class Meta:
        model = Colaborador
        fields = ['nome']

py views.:

from django.shortcuts import render, redirect
from .forms import FormUsuario, FormColaborador, FormEmail

def Cadastro(request):
    data = {}

    if request.method == "POST":
        data['colaborador'] = FormColaborador(request.POST, None)
        data['usuario'] = FormUsuario(request.POST, None)
        data['email'] = FormEmail(request.POST, None)

        if data['colaborador'].is_valid():
            colaborador = data['colaborador'].save(commit=False)
            id = colaborador.id
            if data['usuario'].is_valid():
                usuario = data['usuario']
                usuario.colaboradorId = id
                if data['email'].is_valid():
                    email = data['email']
                    email.colaboradorId = id
                    colaborador.save()
                    usuario.save()
                    email.save()
                    return redirect('lista')
    else:
        data['colaborador'] = FormColaborador()
        data['usuario'] = FormUsuario()
        data['email'] = FormEmail()

    return render(request, 'cadastro.html', data)

html register.:

<form action="" method="POST">
    {% csrf_token %}
    {{ colaborador.as_p }}
    {{ usuario.as_p }}
    {{ email.as_p }}
    <button class="btn btn-success">Enviar</button>
</form>

1 answer

0

The reason for the error is that you are "saving" the collaborator with commit=False, thus:

colaborador = data['colaborador'].save(commit=False)

The commit=False causes the object to not be persisted in the database, which in turn causes it to does not have an id. So that’s why when you try to assign the contribuidor.id then the id it’s actually going to be None, which will cause the Constraint error.

So to resolve, just remove the commit:

colaborador = data['colaborador'].save()

Browser other questions tagged

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