Currenly我可以通过任何网址获取当前登录用户的图库
example.com/user/gallery
example.com/user123/gallery
example.com/312any-thing/gallery
这不是我想要的。我想要的是首先检查,如果用户存在,然后通过ArchiveIndexView
提供所需的图库。
如何在username
课程中获取example.com/{{}}/gallery的username
部分才能实施
ArchiveIndexView
user = get_object_or_404(UserProfile, slug=username)
我尝试使用以下网址从网址获取# project urls
urlpatterns = [
url(r'^(?P<slug>[\w.-]+)/', include('profiles.urls', namespace='profiles_user')),
]
# app.urls
urlpatterns = [
url(r'^$', views.ProfileDetailView.as_view(), name='profiles_home'),
url(r'^gallery/$', views.ProfileGalleryArchiveIndexView.as_view(), name='profiles_gallery'),
]
# app.views
class ProfileGalleryDateView(object):
date_field = 'date_added'
allow_empty = True
class ProfileGalleryArchiveIndexView(ProfileGalleryDateView, ArchiveIndexView):
def get_queryset(self):
user = self.request.user # here I want to get username from url
user = get_object_or_404(UserProfile, slug=username)
return Gallery.objects.filter(galleryextended__user=user).is_public()
:
username
但def get_context_data(self, **kwargs):
context = super(ProfileDetailView, self).get_context_data(**kwargs)
user = get_object_or_404(UserProfile, pk=kwargs['object'].pk)
的执行速度早于get_queryset
。
答案 0 :(得分:1)
您的网址会将用户名捕获为slug
,因此您可以从self.kwargs['slug']
获取该用户名。