我想在一个URL路径中添加多个子域,如下所示:
path('<slug:firstslug>/<slug:secondslug>/<slug:thirdslug>/', views.mydetailview, name='detailview')
我尝试了很多方法,但没有奏效。我想使用普通的基于类的视图。所有 slug 都来自同一应用程序的相同型号。
以下解决方案对我有用;
我的应用> models.py:
class Model(models.Model):
constructor = models.ForeignKey(Constructor, on_delete=models.CASCADE)
model_name = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=250, unique=True)
model_image = models.ImageField(upload_to='photos',
blank=True)
我们需要定义一个函数来接收所需的 slug 作为参数
def get_version(self):
return reverse('selected_versions', args=[self.constructor.slug,
self.slug])
我的应用> views.py:
def selected_versions(request, constructor_slug=None, model_slug=None):
constructors = None
models = None
versions = None
if (constructor_slug != None and model_slug != None):
constructors = get_object_or_404(Constructor, slug=constructor_slug)
models =get_object_or_404(Model, slug=model_slug)
versions=Version.objects.filter(constructor=constructorsi,
model=models)
else:
versions=Version.objects.all()
context={
'version': versions,
}
return render(request, 'versions.html', context)
我的应用> urls.py:
urlpatterns = [
path('<slug:constructor_slug>/<slug:model_slug>/', views.selected_versions,
name='selected_versions'),
]