【问题标题】:How to get user_url part being at site.com/user_url/gallery/slug in case of DetailView?在 DetailView 的情况下,如何获取位于 site.com/user_url/gallery/slug 的 user_url 部分?
【发布时间】:2017-01-15 15:55:57
【问题描述】:

我想使用类似的方式将模板中的链接从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 参数而不是--&gt;&gt;&gt;????&lt;&lt;&lt;--- 以获取site.com/user_url/gallery 之类的url。

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

【问题讨论】:

    标签: django django-templates django-urls


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-10-20
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      相关资源
      最近更新 更多