0

I want to save the Portfolio products details in PortfolioProducts model in django

I have models like below:

class Product(models.Model):
    name = models.CharField(max_length=255,null=True, verbose_name ='Name')


class Portfolio(models.Model):
    name = models.CharField(max_length=100, blank=True, null=True, verbose_name ='Name')

class PortfolioProducts(models.Model):

    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, verbose_name ='Portfolio')
    product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name ='Product')

Portfolio form:

class PortfolioForm(forms.ModelForm):
    class Meta:
        model = Portfolio
        fields = ['name']

My view file:

def edit(request):
    portfolio_form = PortfolioForm

    if request.method=="POST":
        portfolio_id=request.POST.get('portfolio_id')
        portfolio_detail = Portfolio.objects.get(pk=portfolio_id)

        pform = portfolio_form(request.POST, instance=portfolio_detail)
        if pform.is_valid():
            portfolio = pform.save(commit = False)
            portfolio.save()

            products=request.POST.getlist('product_id[]')
            for product in products:
                ppform = PortfolioProducts(product_id=product, portfolio_id=portfolio_id)
                port_product = ppform.save()

I am trying to save and update the Portfolio products like this, but is adding products to portfolio multiple time.

Jaimin Rlogical
  • 256
  • 1
  • 11

2 Answers2

1

Well, you don't need to update PortfolioProduct for updating Portofilio. Because even if you update Portfolio, its primary key remains same as before. So the relationship remains the same.

But, in your case, if PortofolioProduct does not exist for a product in products and Portfolio object, then you can create one like this:

 for product in products:
       ppform, _ =  PortfolioProducts.objects.get_or_create(product_id=product, portfolio_id=portfolio_id)

Update

From comments: you need to either remove def save(self): methods from you Model(Because you are not doing anything particular in those save methods) or if intend to keep you save() methods, then you need to call the super properly, like this:

class Product(models.Model):
    name = models.CharField(max_length=255,null=True, verbose_name ='Name')

    def save(self, *args, **kwargs):
        super(Product, self).save(*args, **kwargs)

class Portfolio(models.Model):
    name = models.CharField(max_length=100, blank=True, null=True, verbose_name ='Name')

    def save(self, *args, **kwargs):
        super(Portfolio, self).save(*args, **kwargs)

class PortfolioProducts(models.Model):
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, verbose_name ='Portfolio')
    product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name ='Product')

    def save(self, *args, **kwargs):
        super(PortfolioProducts, self).save(*args, **kwargs)
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • I am getting this error : save() got an unexpected keyword argument 'force_insert' – Jaimin Rlogical May 02 '19 at 07:26
  • can you add the full stacktrace please? Also you don't need to call `ppform.save()` in for loop. because its already being saved using [get_or_create](https://docs.djangoproject.com/en/2.1/ref/models/querysets/#get-or-create). – ruddra May 02 '19 at 07:31
  • can you add the full stacktrace please? I don't have idea how to do this. Also I have removed this : ppform.save() – Jaimin Rlogical May 02 '19 at 08:16
  • Can you post all the contents of error page(the page where you got ` save() got an unexpected keyword argument 'force_insert' `) – ruddra May 02 '19 at 09:34
  • Thanks. Are you overriding your `save()` method in your Model? Also this answer may help: https://stackoverflow.com/questions/12760262/django-autoupdate-user-save-got-an-unexpected-keyword-argument-force-insert – ruddra May 02 '19 at 09:40
  • @JaiminRlogical please see the update section of my answer. Hope it helps. :) – ruddra May 02 '19 at 09:54
0

Yes, I also got stuck with the same issue in my django project. The thing it does in my case was everytime the user tries to update his/her profile, it created a new one, this is because of the Foreign Key to it. I fixed the issue by deleting the previous user profile (in your case it's portfolio) every time the user updates it.

class UserEdit(TemplateView):
template_name = 'accounts/homee.html'

def get(self, request):
    form = UserProfilee()
    ppp = UserProfile.objects.get(user=request.user)
    return render(request, self.template_name, {'form': form, 'ppp': ppp})

def post(self, request):
    form = UserProfilee(request.POST, request.FILES)
    pppp = UserProfile.objects.get(user=request.user)
    if form.is_valid():
        post = form.save(commit=False)
        post.user = request.user
        if not post.image:
            post.image = pppp.image
        UserProfile.objects.filter(user=post.user).delete()
        post.save()
        return redirect('/home/homepage/')

    args = {'form': form}
    return render(request, self.template_name, args)

As you see,I filter the user and delete the user profile whenever user updates his/her profile thus leaving only 1 user profile.