Django 更改登录表单的默认路径

时间:2021-04-26 19:36:31

标签: django django-templates

Django 默认登录路径为registration/login.html。 问题是我想使用主索引页面内的登录表单,而不是其他页面。

对于这个登录页面,views.py中没有函数,URLS.py中没有路径或url

如果我将以下代码放在 webpage/registration/login.html 中,登录表单将起作用。但是如果我把代码放在 webpage/index.html 中,登录是不成功的。

  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Login</button>
  </form>

如何将默认登录路径更改为在 webpage/index.html 上查看而不是在 registration/login.html 上查看?

更新: 我把下面的代码按照这里的建议。它将登录 url 更改为 index.html 地址。但在那里登录仍然不起作用。

from django.contrib.auth.views import LoginView

class WebpageLoginView(LoginView):
    template_name = 'webpage/index.html'

2 个答案:

答案 0 :(得分:0)

如果您使用 django.contrib.auth 模块中的 LoginView,您可以利用 python 继承并将默认模板名称从 registration/login.html 更改为 webpage/index.html,如下所示:

from django.contrib.auth.views import LoginView

class WebpageLoginView(LoginView):
    template_name = 'webpage/index.html'

但是,如果 webpage/index.html 的内容不是静态的并且表单必须处理一些其他数据以呈现响应,那么这不是一个好方法。在这种情况下,您可以覆盖 get_context_dataLoginView 方法并将您的逻辑放在那里,但这不是一个好的做法。

答案 1 :(得分:0)

你可以做的是利用你的请求函数,因为你使用了 CBV。

类似:

from django.contrib,view import generic # confirm that this import is correct.

class WebpageLoginView(generic.View):
    template_name = 'webpage/index.html
    
        def post(request):
            # make your authentication here

只要您的页面使用 get 方法加载,每当页面上的表单发出 post 请求时,它都会被视为尝试登录。