So I am having a problem with adding a ManyToMany Object to my Absolute URL. Below are my models. Check out the Category class. I know I need to get Category title into the URL.
# Category class
class Category(models.Model):
title = models.CharField(max_length=128)
description = models.TextField()
def __unicode__(self):
return self.title
# Product class
class Product(models.Model):
title = models.CharField(max_length=128)
pub_date = models.DateField('date published')
slug_title = models.SlugField(editable=False)
cover_image = models.ImageField(upload_to="images/product/")
image = models.ManyToManyField(Image)
category = models.ManyToManyField(Category)
description = models.TextField()
def save (self):
self.slug_title = slugify(self.title)
super(Product, self).save()
def __unicode__(self):
return self.title
def get_absolute_url(self):
return ('product_view_url', (), {
'category': self.category,
'year': self.pub_date.strftime("%Y"),
'month': self.pub_date.strftime("%m"),
'day': self.pub_date.strftime("%d"),
'id': self.id,
'slug_title': self.slug_title })
get_absolute_url = models.permalink(get_absolute_url)
Here’s the url.py for product_view_url:
url(r'^product/(?P<category>.+)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<id>.+)/(?P<slug_title>.+)/$', index_views.product_detail, name='product_view_url'),
Below is the view:
# Product Detail View
def product_detail(request, id, category, slug_title, year, month, day, template='index/product_detail.html'):
product = get_object_or_404(Product, id=id, slug_title=slug_title)
payload = {'product': product}
return render_to_response(template, payload, context_instance=RequestContext(request))
With this configuration I get a weird URL: ‘http://localhost:8000/product/%3Cdjango.db.models.fields.related.ManyRelatedManager%20object%20at%200x1067d6050%3E/2012/03/07/1/tropical-twizzler/’
I would like to get something like this: ‘http://localhost:8000/product/candies/2012/03/07/1/tropical-twizzler/’
Sorry for being a noob, still learning my way around Django.
The problem is
categoryis a ManyToManyField. By definition, directly accessing ManyToManyField does not give you a single value but a set of values, which we call it ManyRelatedManager. In order to pick out a value out of the manager instance, you should be able to figure it out here.