主页上的 django allauth 登录和注册表单

django allauth login & signup form on homepage

我一直在寻找解决方案有一段时间了,但我无法解决这个问题。我想要完成的是将 allauth 登录和注册表单放在同一页面和主页上,而不是在 /accounts url 下。有没有人有这方面的经验或有他们可以分享的解决方案或为我指明正确的方向?任何帮助将不胜感激。

首先,我们使用 allauth 的注册视图创建自定义视图

from allauth.accounts.views import SignupView
from allauth.accounts.forms import LoginForm


class CustomSignupView(SignupView):
    # here we add some context to the already existing context
    def get_context_data(self, **kwargs):
        # we get context data from original view
        context = super(CustomSignupView,
                        self).get_context_data(**kwargs)
        context['login_form'] = LoginForm() # add form to context
        return context

这里不会为登录表单呈现验证错误,然后我们需要创建一个自定义的 LoginView,但现在让我们继续使用模板

<button id="toggleForms">Toggle Forms</button> 
<form method='post' action='{% url 'yourviewurl %}' id='signup'>
  {% csrf_token %}
  {{ form.as_p }}
  <input type='submit' value='Sign Up'>
</form>

<form method='post' action='{% url 'loginurl' %}' id='login'  hidden="hidden">
  {% csrf_token %}
  {{ login_form.as_p }}
  <input type='submit' value='Log In'>
</form>

添加一些 javascript 来切换这些。 这些动作将表格指向不同的方向。通常我们会为此使用表单集,但由于 All-auth 的注册表单不是 Form 对象,这可能是最快的方法。

这些都在你选择的任何应用程序的views.py中,标签在settings.py、TEMPLATE_DIRS或django1.8[=12中的Dirs列表中定义的模板中=]

这些步骤对我有用 1. 转到 allauth\account\views
loginViewclassget_context_data函数下添加如下代码signup_form上下文渲染到ret

ret.update({"signup_url": signup_url,
                "site": site,                   
                "redirect_field_name": self.redirect_field_name,
                "redirect_field_value": redirect_field_value,
                -->"signup_form":get_form_class(app_settings.FORMS, 'signup',SignupForm)<--
})return ret
  1. 在您的应用中 views.py

    def homepage(request):
        template = 'account/login.html'
        context ={}
        return render(request, template, context)
    
  2. 你的urls.py

    from .views import homepage

    path('', homepage, name='home'),

  3. 在你的 account/login.html

    {% include "account/signup.html" with form=signup_form %}

请参阅 https://github.com/believeohiozua/django-allauth/blob/master/allauth/account/views.py 示例代码

如果您对上述存储库没问题,您可以使用
安装 pip install git+https://github.com/believeohiozua/django-allauth.git