从基于函数的视图返回基于类的视图

时间:2018-11-23 16:47:52

标签: python django

因此,我设置了一个登录视图,成功登录后,我想通过引用另一个基于类的视图转到自己选择的页面。我不确定如何实现这一目标。

登录视图

def login_view(request):
    if request.method == 'POST':
        form =AuthenticationForm(data=request.POST)
        if form.is_valid():
            user=form.get_user()
            login(request,user)
            #Not sure what to do next
            #return HttpResponseRedirect(reverse(request, Dashboard))?   
        else:
            #TODO
    else:
        form = AuthenticationForm()

我要去的仪表板班

class Dashboard(ListView):
    model = models.Note
    template_name = 'notemanager/dashboard.html'

    def get_context_data(self, request,**kwargs):
        context = super().get_context_data(**kwargs)
        notedata = models.Note.objects.filter(added_by = User)
        reminderdata = models.Reminder.objects.filter(added_by = User)
        context['notes'] = notedata
        context['reminder'] = reminderdata

        return context

urls.py

urlpatterns = [
    path('login/',views.Login.as_view(),name="login"),
    path('',views.Dashboard.as_view(), name ="dash")

]

2 个答案:

答案 0 :(得分:1)

通常,重定向的方法是使用所用视图的URL /路由名称。

因此,如果您的urls.py中有类似以下内容:


urlpatterns = [
    re_path('^dashboard$', Dashboard.as_view(), name='dashboard'),
]

您可以重用路由的name部分,以使用redirect向用户发送302重定向:


from django.shortcuts import redirect

def login_view(request):
    if request.method == 'POST':
        form =AuthenticationForm(data=request.POST)
        if form.is_valid():
            user=form.get_user()
            login(request,user)
            #Not sure what to do next
            #return HttpResponseRedirect(reverse(request, Dashboard))?   
            return redirect('dashboard')  # matches the name part of the route in urls.py
        else:
            #TODO
    else:
        form = AuthenticationForm()

n.b。,您的视图也有错误。 request没有get_context_data参数,因此它看起来应该像这样:


class Dashboard(ListView):
    model = models.Note
    template_name = 'notemanager/dashboard.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        notedata = models.Note.objects.filter(added_by = User)
        reminderdata = models.Reminder.objects.filter(added_by = User)
        context['notes'] = notedata
        context['reminder'] = reminderdata

        return context

答案 1 :(得分:1)

在您的views.py中添加重定向,

def login_view(request):
if request.method == 'POST':
    form =AuthenticationForm(data=request.POST)
    if form.is_valid():
        user=form.get_user()
        login(request,user)
        return redirect('dash') #If you have mentioned app_name in urls.py add app_name:dash in place of dash    
    else:
        #TODO
else:
    form = AuthenticationForm()

在urls.py中,

urlpatterns = [
     path('login/',views.Login.as_view(),name="login"),
     path('',views.Dashboard.as_view(), name ="dash"),
]

这会将用户重定向到127.0.0.1:8000/