在django中将网址扩展到另一个网址

时间:2018-01-01 08:48:36

标签: python django

我有一个django应用程序,我可以创建一个类别,从类别中我可以在选择帖子之前选择一个子类别。我还为类别,子类别和帖子创建了slugs,这很好。我现在想要做但却无法实现的是让子类别slug继续在d类别上,如果slug是http://127.0.0.1:8000/house/之后点击一个子类别,我希望在点击帖子后网址看起来像这样在房屋http://127.0.0.1:8000/house/duplex下,dublex是类别房屋的子类别。下面是我的子模型 类

Models.py

class SubCategory(models.Model):
    category = models.ForeignKey(Category, related_name='property', on_delete=models.CASCADE)
    name = models.CharField(max_length=400,db_index=True)
    slug = models.SlugField(max_length=400,db_index=True, unique=True)

    class Meta:
        ordering = ('name',)
        verbose_name = 'subcategory'
        verbose_name_plural = 'subcategories'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('subcategory:property_list_by_subcategory', args=[self.slug])

查看

def index(request, subcategory_slug=None):
    subcategory = None
    subcategories = SubCategory.objects.all()
    properties = Property.objects.filter(available=True)
    if subcategory_slug:
        subcategory = get_object_or_404(SubCategory, slug=subcategory_slug)
        properties = properties.filter(subcategory=subcategory)

    context = {
        'subcategory': subcategory,
        'subcategories': subcategories,
        'properties': properties
    }
    template = 'subcategory/index.html'
    return render(request, template, context)

urls.py

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(?P<subcategory_slug>[-\w]+)/$',views.index, name='property_list_by_subcategory'),
]

将根据要求提供其他代码。

1 个答案:

答案 0 :(得分:0)

创建第三个网址:

url(r'^(?P<subcategory_slug>[\w-]+)/(?P<property_slug>[\w-]+)/$', views.post_view)

然后为此网址创建一个视图:

def post_view(request, subcategory_slug, property_slug):
    # find the subcategory
    subcategory = get_object_or_404(SubCategory, slug=subcategory_slug)
    # find the requested property
    property = get_object_or_404(Property, slug=property_slug, subcategory=subcategory)

   # do something else
   return render(request, template, context)