1

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

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

这是我在模板中调用 auth 表单的地方:

<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>

这是我的 urls.py :

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'),
]

这是我的views.py,我还使用python social auth 来登录用户:

    @login_required
    def index(request):

        form = InfosForm(request.POST or None)

        if form.is_valid():

            #if request.user.is_authenticated:
            #    gituser = request.user.social_auth.filter(provider ='github-oauth2')
            #    extra_data = str(gituser.extra_data['access_token'])

            g = Github(gitkey)

            try:

                orga_name = form.cleaned_data['orga_name']
                org = g.get_organization(orga_name)
                repos = org.get_repos()
                reposList = []
                totalCommits = []
                #Transformation de la PaginatedList en liste classique pour manipuler   facilement les repos
                for repo in repos:
                    commitsList = repo.get_stats_participation().all
                    languages = repo.get_languages()
                    if not languages:
                        top_language = ''
                    else:
                        top_language = max(languages.keys(), key=(lambda key: languages[key]))
                    repository = Repository(titre=repo.name, starsgazers=repo.stargazers_count, top_language=top_language)
                    if len(commitsList) >= 2:
                        repository.commits_this_week = commits_this_week=commitsList[-1]
                        repository.commits_last_week = commits_last_week=commitsList[len(commitsList)-2]
                    reposList.append(repository)
                reposList.sort(key=lambda x: x.starsgazers, reverse=True)
                reposList = reposList[:10]
                #django jchart
                envoi = True

            except UnknownObjectException :
                erreur = True

        return render(request,'gitInsights/index.html', locals())

    def get_total_commits_last_week(reposList):

        totalCommits = []
        for repo in reposList:
            totalCommitsAllWeeks = repo.get_stats_participation().all
            totalCommits.append(totalCommitsAllWeeks[-1])

        return totalCommits

    @login_required
    def settings(request):
        user = request.user

        try:
            github_login = user.social_auth.get(provider='github')
        except UserSocialAuth.DoesNotExist:
            github_login = None

        can_disconnect = (user.social_auth.count() > 1 or user.has_usable_password())

        return render(request, 'settings.html', {
            'github_login': github_login,
            'can_disconnect': can_disconnect
        })

    @login_required
    def password(request):
        if request.user.has_usable_password():
            PasswordForm = PasswordChangeForm
        else:
            PasswordForm = AdminPasswordChangeForm

        if request.method == 'POST':
            form = PasswordForm(request.user, request.POST)
            if form.is_valid():
                form.save()
                update_session_auth_hash(request, form.user)
                messages.success(request, 'Your password was successfully updated!')
                return redirect('password')
            else:
                messages.error(request, 'Please correct the error below.')
        else:
            form = PasswordForm(request.user)
        return render(request, 'password.html', {'form': form})


    def informations_legales(request):
        return render(request, 'gitInsights/informations_legales.html')

提前感谢!

4

1 回答 1

6

您可以像这样扩展 AuthenicationForm :

表格.py:

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

您可以检查值:

视图.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- 您只需传入authentication_formurls: urls.py:

from .forms import AuthenticationFormWithRequiredField

urlpatterns = [
    # ...
    path('login/', LoginView.as_view(template_name='login', authentication_form=AuthenticationFormWithRequiredField), name='login'),
]
于 2019-05-17T09:17:37.277 回答