Django为不同的网址读取相同的CBV

时间:2019-05-06 08:01:19

标签: python django django-class-based-views

我在视图中使用TamplateView,因此当用户登录时,它将重定向到他的主页。

我有两个应用程序:app_manager(负责登录和注册)和app_user,我们可以在其中找到用户的所有功能。

app_manager.views:

return HttpResponseRedirect(reverse("app_user:switcher_user", args=(slugify(username_instance),)))

app_user.views:

def switcher_user(request, username):
    print(username)
    qs = User.objects.filter(username=username)
    print(qs)
    if not qs.exists():
        print("user not found")
        return HttpResponseRedirect(reverse('app_user:access_denied'))
    else:
        print("user already exists")
        return user_index.as_view()(request)

class user_index(LoginRequiredMixin,TemplateView):
    print("this is from user_index")
    template_name = "app_user/user_index.html"
    model = User
    context_object_name = 'user'


class ProfilView(LoginRequiredMixin,TemplateView):
    template_name = "app_user/user_profil.html"

class GroupsView(LoginRequiredMixin,ListView):
    template_name = "app_user/user_groups.html"

app_user.urls:

app_name ="app_user"

urlpatterns = [
    re_path(r'^(?P<username>[\w.@+-]+)/', views.switcher_user, name='switcher_user'),
    re_path(r'^(?P<username>[\w.@+-]+)/profil', views.ProfilView.as_view(), name='user_profil'),
    re_path(r'^(?P<username>[\w.@+-]+)/groups', views.GroupsView.as_view(), name='user_groups'),

在我的app_user应用程序中,我有一个模板文件夹,在其中可以找到该类型用户的所有html页面。在我的base.html中:

<li> <a href="{% url 'app_user:user_profil' username=user.username %}">Profil</a></li>

<li> <a href="{% url 'app_user:user_groups' username=user.username %}">Groups</a></li>

这里的问题是,当我单击“ Profil”或“组”以转到“性能文件”页面或“组”页面时,我在浏览器地址栏中获得了正确的url,但使用了错误的html文件。它总是读取相同的视图,即switcher_user和user_index,并为我带来相同的页面“ user_index.html”。

1 个答案:

答案 0 :(得分:0)

您没有终止正则表达式。

re_path(r'^(?P<username>[\w.@+-]+)/$', ...)
相关问题