Search code examples
pythondjangodjango-viewsdjango-taggit

django-taggit obtain tags string from form


I trying to use django-taggit as a tag model.

model.py

class Product(models.Model):
    product_no = models.IntegerField(primary_key=True)
    ... 
    tags = TaggableManager(blank=True)

views.py

def action(request):
    product = Product()

    user = User.objects.get(id=request.user.id)
    product.seller_username = user
    ...

    product.save()

    tag_list = taggit.utils._parse_tags(request.POST['tags'])
    product.tags.add(*tag_list)

When I call method product.tags.add(), I'm getting an error say

Product objects need to have a primary key value before you can access their tags

Many solutions I find inform me to put product.save() before product.tags.add() to make pk available before access many-to-many field. I've try it and still the error.

Note: the save() method work properly. It create new object in Product list and can be see in admin interface.


Solution

  • It seem that I have to change

    product_no = models.IntegerField(primary_key=True)
    

    to

    product_no = models.AutoField(primary_key=True)
    

    and it's fixed.