【发布时间】:2021-09-29 09:49:00
【问题描述】:
在这个问题上真的很挣扎。由于某种原因,我无法让我的 URL 加载正确的视图。该站点正确加载了主页,但是当我添加扩展以访问我的另一个应用程序时,它只是重新加载了主页。它不会抛出任何错误或任何东西,它只是会直接进入正确的页面。
这是我的基本 URL 文件:
path('admin/', admin.site.urls),
path('', blog_views.home),
path('<username>/', include('blog.urls')),
path('community/', include('community.urls')),
Blog URL 文件的开头:
path('', LogListView.as_view(), name='log'),
这是Blog 视图文件:
@login_required
def home(request):
user_name = request.user.username
return HttpResponseRedirect(f'{user_name}/')
class LogListView(LoginRequiredMixin, ListView):
model = Post
template_name = 'blog/log-main.html'
login_url = 'login/'
context_object_name = 'posts'
ordering = ['-date_added']
def get_context_data(self, **kwargs):
context = super(LogListView, self).get_context_data(**kwargs)
context['posts'] = Post.objects.filter(user = self.request.user)
return context
上面的 home 函数通过将用户名放在 URL 路径的开头自动将每个用户引导到他们的特定主页。
那么这里是我的Community 应用网址文件:
path('', CommunityListView.as_view(), name='community'),
还有Community查看文件:
class CommunityListView(LoginRequiredMixin, ListView):
model = Post
template_name = 'community/community.html'
context_object_name = 'postss'
ordering = ['-date_added']
def get_queryset(self):
qs = super().get_queryset()
active_user = self.request.user
active_user_following = active_user.following.values_list('user_id', flat=True)
following_user_objects = []
for id in active_user_following:
followed = User.objects.get(id=id)
following_user_objects.append(followed)
print(followed)
print(following_user_objects)
print(active_user_following)
return WILT.objects.filter(user__in=following_user_objects)
如上所述,当我将/community/ 添加到 URL 路径时,它会重新加载主页。我已经经历了几个小时没有运气。
【问题讨论】:
-
您是如何管理需要登录的......当您尝试访问主路由时,用户是否已登录?