0

I have a simple app, where a user has multiple businesses, and each business has multiple products, what I´m trying to do is a make product creatView, where i can select a business from the ones owned by the current user. I tryed editing the init() method of the ModelForm like this:

class Producto_Form(forms.ModelForm):
    class Meta:
        model = Producto_Model
        fields = ("Nombre_Producto","Negocio","Descripcion_Producto",'Precio_Producto','Tags',"Foto")

    def __init__(self, *args, **kwargs):
        super(Producto_Form, self).__init__(*args, **kwargs)
        self.fields['Negocio'].queryset = Negocio_Model.objects.all().filter(Administrador_id=kwargs['user'].id)

and then i changed the get_form_kwargs from the create product view like this:

class crear_producto(LoginRequiredMixin, CreateView):

    template_name = "tienda/crear_producto.html"
    form_class= Producto_Form
    success_url = reverse_lazy('tienda_app:crear_producto')
    login_url = reverse_lazy('register_app:logIn')

    def get_form_kwargs(self, *args, **kwargs):
        kwargs = super().get_form_kwargs(*args, **kwargs)
        kwargs['user'] = self.request.user
        return kwargs

I was following this question but I keep getting the error __init__() got an unexpected keyword argument 'user'

1 Answers1

0

So everything is almost fine but you must pass the user variable to the form init as the kwargs, also, on the queryset dont call it like kwargs['user'] and just call user, something like this:

def __init__(self, user, *args, **kwargs):
        super(Producto_Form, self).__init__(*args, **kwargs)
        self.fields['Negocio'].queryset = Negocio_Model.objects.all().filter(Administrador_id=user.id)

also I changed the super() constructor on the get_form_kwargslike this:

def get_form_kwargs(self, *args, **kwargs):
    kwargs = super(crear_producto, self).get_form_kwargs(*args, **kwargs)
    kwargs['user'] = self.request.user
    return kwargs