【问题标题】:Django: Absolute URL With ManyToMany ObjectDjango:具有多对多对象的绝对 URL
【发布时间】:2012-03-24 14:35:03
【问题描述】:

所以我在将 ManyToMany 对象添加到我的绝对 URL 时遇到了问题。下面是我的模型。查看类别类。我知道我需要将类别标题添加到 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)

这是 product_view_url 的 url.py:

    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'),

下面是视图:

    # 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))

通过这个配置,我得到一个奇怪的 URL:'http://localhost:8000/product/%3Cdjango.db.models.fields.related.ManyRelatedManager%20object%20at%200x1067d6050%3E/2012/03/07/ 1/tropical-twizzler/'

我想得到这样的东西:'http://localhost:8000/product/candies/2012/03/07/1/tropical-twizzler/'

对不起,我是个菜鸟,我还在学习 Django。

【问题讨论】:

  • 你能发布你的 urls.py 吗?我需要看看你是怎么定义'product_view_url'的。

标签: django django-urls django-orm


【解决方案1】:

问题是category 是一个ManyToManyField。根据定义,直接访问 ManyToManyField 不会给你一个值,而是一组值,我们称之为 ManyRelatedManager。为了从管理器实例中提取一个值,您应该能够找出here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 2020-06-16
    • 2011-10-23
    相关资源
    最近更新 更多