如何扩展Django AuthenticationForm

时间:2019-05-17 09:07:07

标签: python django pygithub

我正在编写一个Web应用程序,我想在Django的AuthenticationForm中添加一个必需的复选框

我不知道如何扩展(或覆盖?)AuthenticationForm。

在这里我在模板中调用auth表单:

df2 = DataFrame({'Condition': ['1A', '1A-1A', '1A, 2B', '1A-2B', '3C, 1A-2B']})

df2
    Condition
0   1A
1   1A-1A
2   1A, 2B
3   1A-2B
4   3C, 1A-2B

这是我的urls.py:

<h2>Login</h2>
<form method="post">
   {% csrf_token %}
   {{ form.as_p}}
   <button type="submit" class="btn btn-success">Login</button>
 </form>
  <br>
 <p><strong>-- OR --</strong></p>
 <a href="{% url 'social:begin' 'github' %}">Login with GitHub</a><br>
</body>

这是我的views.py,我也正在使用python social auth登录用户:

from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from django.conf.urls import url, include
from gitInsights import views as core_views
from django.contrib.auth.views import LoginView

    urlpatterns = [
    path('admin/', admin.site.urls),
    path('gitInsights/', include('gitInsights.urls')),
    path('login/', auth_views.login, name='login'),
    path('logout/', auth_views.logout, name='logout'),
    url(r'^auth/', include('social_django.urls', namespace='social')),
    url(r'^settings/$', core_views.settings, name='settings'),
    url(r'^settings/password/$', core_views.password, name='password'),
    path('', core_views.index, name='index'),
    path('informations-legales/', core_views.informations_legales, name='informations_legales'),
]

预先感谢!

1 个答案:

答案 0 :(得分:1)

您可以像这样扩展AuthenicationForm:

forms.py:

class AuthenticationFormWithRequiredField(AuthenticationForm):
    required_checkbox = forms.BooleanField(required=True)

您可以检查值:

views.py:

class SampleLoginView(LoginView):
    form_class = AuthenticationFormWithRequiredField

    def form_valid(self, form):
        checkbox = form.cleaned_data['required_checkbox']
        print(checkbox)
        return super().form_valid(form)

您不必扩展LoginView-您只需在URL中添加pass authentication_form: urls.py:

from .forms import AuthenticationFormWithRequiredField

urlpatterns = [
    # ...
    path('login/', LoginView.as_view(template_name='login', authentication_form=AuthenticationFormWithRequiredField), name='login'),
]