Home > Net >  How to add items to ManyToMany field from Queryset
How to add items to ManyToMany field from Queryset

Time:08-25

What I am trying to achieve is to get the title that the user inserted in the form and save it in all components that are currently in the cart.

This piece of code contains the items that are currently in the cart:

get_components = user.cart_component.all()

It gives me a queryset like this:

<QuerySet [<ProductComponents: component 1>, <ProductComponents: component 2>, <ProductComponents: component 3>]>

I am also able to get the title from the form by using get('title').

What I am struggling with is how can I add all components from get_component to the newly created template. I am getting the following error:

Field 'id' expected a number but got 'test template'.

my post method in TemplateView:

def post(self, *args, **kwargs):
    ce_template_form = SaveAsTemplateForm(data=self.request.POST)

    if ce_template_form.is_valid():
        template_title = ce_template_form.cleaned_data.get('title')
        user = self.request.user
        get_components = user.cart_component.all()
        for component in get_components:
            component.template.add(template_title) # how can I pass id here?
        ce_template_form.save()
        return redirect('cart')

models.py

class UserTemplate(models.Model):
    title = models.CharField(max_length=200)

class CostCalculator(models.Model):
    [...]
    template = models.ManyToManyField(UserTemplate, related_name='user_template', blank=True, default='-')

CodePudding user response:

You need to get UserTemplate object to pass it to add (you didn't show your forms and models so I'm little guessing here)

so in post method in TemplateView:

def post(self, *args, **kwargs):
    ce_template_form = SaveAsTemplateForm(data=self.request.POST)
    if ce_template_form.is_valid():
        template_title = ce_template_form.cleaned_data.get('title')
        template_object = UserTemplate.objects.get(title=template_title)
        user = self.request.user
        get_components = user.cart_component.all()
        for component in get_components:
            component.template.add(template_object) # how can I pass id here?
        ce_template_form.save()
        return redirect('cart')
  • Related