Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在django中从视图中传递自定义身份验证表单?_Python_Django_Authentication_Django Forms_Django Authentication - Fatal编程技术网

Python 如何在django中从视图中传递自定义身份验证表单?

Python 如何在django中从视图中传递自定义身份验证表单?,python,django,authentication,django-forms,django-authentication,Python,Django,Authentication,Django Forms,Django Authentication,我正在尝试将我创建的自定义身份验证表单传递给auth.views.login 我找到的所有教程都是通过url.py中的url()完成的,并且带有登录视图的url,例如: url(r'^login/$', auth.views.login,{'authentication_form':MyAuthenticationForm}) 但是我希望url与索引url相同,如果用户经过身份验证,则显示索引,否则使用自定义身份验证表单显示登录表单 这是我的视图。py: from django.shortcu

我正在尝试将我创建的自定义身份验证表单传递给auth.views.login

我找到的所有教程都是通过url.py中的url()完成的,并且带有登录视图的url,例如:

url(r'^login/$', auth.views.login,{'authentication_form':MyAuthenticationForm})
但是我希望url与索引url相同,如果用户经过身份验证,则显示索引,否则使用自定义身份验证表单显示登录表单

这是我的视图。py

from django.shortcuts import render
from django.contrib.auth import views as auth_views


def cp(request):
  if request.user.is_authenticated():
      return render(request, 'index.html')

  # How to pass my custom authentication form ?
  return auth_views.login(request)

这是可行的,但我如何告诉django我的自定义身份验证表单?

我建议您保留
/login/
作为登录url,但使用decorator作为索引视图。当新用户访问您的索引url时,他们将被重定向到您的登录页面,然后在登录后返回到索引url

from django.contrib.auth.decorators import login_required

@login_required
def index(request):
   return render(request, 'index.html')
这种方法在Django中非常典型,并且比使用索引url处理登录更简单。如果确实要从索引页调用登录视图,则应使用url模式中相同的kwarg
authentication\u表单

return auth_views.login(request, authentication_form=MyAuthenticationForm)

我建议您保留
/login/
作为登录url,但使用decorator作为索引视图。当新用户访问您的索引url时,他们将被重定向到您的登录页面,然后在登录后返回到索引url

from django.contrib.auth.decorators import login_required

@login_required
def index(request):
   return render(request, 'index.html')
这种方法在Django中非常典型,并且比使用索引url处理登录更简单。如果确实要从索引页调用登录视图,则应使用url模式中相同的kwarg
authentication\u表单

return auth_views.login(request, authentication_form=MyAuthenticationForm)

谢谢,成功了。我是django的新手,但我注意到,有时当我做一些更改时,即使我重新启动服务器,它也不适用。这听起来像是一个单独的问题,所以我不能帮你。你不需要。我只是说:)谢谢,这很有效。我是django的新手,但我注意到,有时当我做一些更改时,即使我重新启动服务器,它也不适用。这听起来像是一个单独的问题,所以我不能帮你。你不需要。我只是说:)