The ManytoMany relationship is not performed

1

I have the following models :

class Persona(models.Model):
    cedula = models.CharField(max_length=12, unique=True, null=False, blank=False)
    rol = models.ManyToManyField('Rol')
    cuenta = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, blank=True)

class Evaluador(Persona):
    email = models.EmailField(max_length=60, unique=True, null=False, blank=True)

class Usuario(Evaluador):
    nombre = models.CharField(max_length=50)
    apellido = models.CharField(max_length=50)
    cargo = models.CharField(max_length=30)

class Rol(models.Model):
    nom_rol = models.CharField(max_length=20)
    evalua = models.BooleanField(default=True)

and this is my view :

class UsuarioCreate(CreateView):
    model = Usuario
    template_name = 'pages/usuario_form.html'
    form_class = UsuarioForm
    second_form_class = UserCreationForm
    success_url = reverse_lazy('Principal:usuarios_lista')

    def get_context_data(self, **kwargs):
        context = super(UsuarioCreate, self).get_context_data(**kwargs)
        if 'form' not in context:
            context['form'] = self.form_class(self.request.GET)
        if 'form2' not in context:
            context['form2'] = self.second_form_class(self.request.GET)
        return context

    def post(self, request, *args, **kwargs):
        self.object = self.get_object
        form = self.form_class(request.POST)
        form2 = UserCreationForm(request.POST)
        if form.is_valid() and form2.is_valid():
            usuario = form.save(commit=False)
            usuario.cuenta = form2.save()
            usuario.save()
            return HttpResponseRedirect(self.get_success_url())
        else:
            return self.render_to_response(self.get_context_data(form=form, form2=form2))

this is how it looks in the template:

The problem is that after having filled in all the fields, the relation of Persona with cuenta is successful, but the relation with rol is not realized.

In console does not throw me any error and when reviewing the database the intermediate table of role-person is empty. I'm doing this from an html not from the django admin.

    
asked by Renato Poma 08.09.2017 в 19:34
source

1 answer

0

The solution to the problem after so much searching was achieved by adding a

  

form.save_m2m ()

later

  

user.save ()

It must be added when a commit=False is used since this does not save the association ManyToMany

    
answered by 11.09.2017 в 06:18