NOT NULL constraint failed: worker_worker.rol_id

1

I have the following error NOT NULL constraint failed: worker_worker.rol_id  when saving the data using a modelForm

Model

class Trabajador(models.Model):
    nombres = models.CharField(max_length=50)
    apellido_paterno = models.CharField(max_length=50)
    apellido_materno = models.CharField(max_length=50)
    rol = models.ForeignKey('Rol', on_delete=models.CASCADE)
    def __str__(self):
        return self.nombres

form

class Trabajadorform(ModelForm):

    class Meta:
        model = Trabajador
        fields = ['nombres', 'apellido_paterno', 'apellido_materno']

view

from django.shortcuts import redirect
from django.shortcuts import render
from .forms import Trabajadorform


def registrar(request):
    if request.method == 'POST':
        form = Trabajadorform(request.POST)
        if form.is_valid():
            print('formulario valido')
            trabajador = form.save()
            trabajador.save()
            #return redirect('post_detail')
    else:
        form = Trabajadorform

    return render(request, 'registrar_trabajador.html', {'form': form})
    
asked by Marcos Mauricio 24.04.2018 в 04:00
source

1 answer

1

You have the empty role field. Django by default puts all the required fields. I do not know if that's how you want it, so I'll give you 2 solutions:

Empty Role solution

Modify the role field in your model by this:

class Trabajador(models.Model):
    nombres = models.CharField(max_length=50)
    apellido_paterno = models.CharField(max_length=50)
    apellido_materno = models.CharField(max_length=50)
    rol = models.ForeignKey('Rol', on_delete=models.CASCADE, blank=True, null=True)

    def __str__(self):
        return self.nombre

Non-empty Role Solution

Add the field to ModelForm so that you can add a role to that worker or you can add your own role within the view by doing trabajador.rol = Rol.objects.get(id=id_ejemplo) and then apply the save()

    
answered by 24.04.2018 / 10:57
source