如果是DetailView,如何将user_url部分发送到site.com/user_url/gallery/slug?

时间:2016-09-07 20:44:17

标签: django django-templates django-urls

我希望使用以下内容将site.com/user_url/gallery/slug中的模板链接回site.com/user_url/gallery/

<a href="{% url 'profiles_user:profiles_gallery' -->>>????<<<--- %}" 
class="btn btn-default">"Come back to all galleries and photos"</a>

我需要提供-->>>????<<<---参数来代替user_url,以便将此类网址设为site.com/user_url/gallery

# site.com/user_url/gallery/slug - gallery details
class ProfileGalleryDetailView(DetailView):
    template_name = 'profiles/gallery_detail.html'

    def get_queryset(self):
        print(self.__dict__)
        user = get_object_or_404(UserProfile, user_url=self.kwargs['user_url'])
        return Gallery.objects.filter(galleryextended__user=user, slug=self.kwargs['slug']).on_site().is_public()

print(self.__dict__)告诉我:

{'args': (), 'kwargs': {'slug': 'time-sleep', 'user_url': '1-plus-1'}, 
'request': <WSGIRequest: GET '/1-plus-1/gallery/time-sleep/'>, 
'head': <bound method BaseDetailView.get of <profiles.views.ProfileGalleryDetailView object at 0x7fe912b41860>>}

如何从模板中的kwargs中获取'user_url': '1-plus-1'?我是否需要使用get_context_data才能将user_url添加到上下文?

# Core urls.py
urlpatterns = [
    url(r'^(?P<user_url>[\w.-]+)/', include('profiles.urls', namespace='profiles_user')),
]

# profiles.urls
urlpatterns = [
    url(r'^$', views.ProfileDetailView.as_view(), name='profiles_home'),
    url(r'^gallery/$', views.ProfileGalleryArchiveIndexView.as_view(), name='profiles_gallery'),
    url(r'^gallery/(?P<slug>[\-\w]+)/$', views.ProfileGalleryDetailView.as_view(), name='profiles_gallery-details'),
]

1 个答案:

答案 0 :(得分:0)

在基于类的视图中,get_context_data方法将视图包含为view。因此,您可以使用user_url访问view.kwargs.user_url kwarg。

<a href="{% url 'profiles_user:profiles_gallery' view.kwargs.user_url %}">