Reputation: 9289
I have searched and read through the internet trying to figure out this problem. Thank you for any advice on this issue.
I have been having problems adding a list of objects to another object in Django. I have an object 'category' and a list of objects 'subcategory', but when I try to put them together as a package 'ad', there is a TypeError: 'subcategory' is an invalid keyword argument for this function
.
Here is the view:
def create_in_category(request, slug):
category = get_object_or_404(Category, slug=slug)
subcategory = SubCategory.objects.all()
ad = Ad.objects.create(category=category, subcategory=subcategory, user=request.user,
expires_on=datetime.datetime.now(), active=False)
ad.save()
What am I missing to be able to get all of these elements together? Thanks very much for sharing your knowledge.
Edit: added the models.
class Category(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField()
def __unicode__(self):
return self.name + u' Category'
class SubCategory(models.Model):
name = models.CharField(max_length=50, unique=True)
category = models.ManyToManyField(Category)
def __unicode__(self):
return self.name + u' SubCategory'
Upvotes: 0
Views: 530
Reputation: 10919
i'm not positive what you are doing or why, but just to put my 2 cents in:
If you are going to do categories w/ hierarchy (unless there is something different (aside from position in the hierarchy) maybe you should use something like https://github.com/django-mptt/django-mptt/
class Category(MPTTModel) :
"""initial Category model"""
title = models.CharField(
verbose_name = _(u'Title'),
help_text = _(u'This category.'),
max_length = 255
)
slug = models.SlugField(
verbose_name = _(u'Slug'),
help_text = _(u'Unique identifier for this category.'),
max_length = 255,
unique = True
)
parent = models.ForeignKey(
'self',
null = True,
blank = True,
default = None,
verbose_name = _(u'Parent Category')
)
class MPTTMeta:
order_insertion_by = ['title', ]
class Meta:
verbose_name = _(u'Category')
verbose_name_plural = _(u'Categories')
def __unicode__(self):
return '%s' % (self.title,)
then you can use all of the fancy hierarchy building tools that MPTT gives you
Upvotes: 2
Reputation: 599610
Using my crystal ball, I can tell that subcategory
is for some reason a ManyToMany relation, and you can't pass that in on instantiation (because it needs a saved instance on both ends before the relationship can be created). Instantiate and save the Ad
first, then add the relationship with ad.subcategory.add(*subcategory)
As to whether that relationship should in fact be a ManyToMany at all is another question (what would it mean for a subcategory to be able to belong to multiple categories?).
Upvotes: 1