Custom “authentication_form” does not apply bootst

2019-08-18 09:24发布

问题:

I'm attempting to apply bootstrap to a django login form. I have scoured google for hours and pretty much everyone is saying the same thing, which is to set the custom authentication_form in urls.py, override the username and password fields in custom login form and pass the class through the widget's attrs parameter. I have done this but django still isn't applying the form-control class to my input fields. I'm not quite sure what is going wrong. The form still renders, but without applying the bootstrap styling.

urls.py

from django.conf.urls import url
from django.contrib.auth.views import LoginView, LogoutView, 
    PasswordChangeView, PasswordChangeDoneView, \
    PasswordResetView, PasswordResetDoneView, 
    PasswordResetConfirmView, PasswordResetCompleteView

from account.forms import LoginForm
from account.views import dashboard

urlpatterns = [
    url(r'^$', dashboard, name='dashboard'),
    url(r'^login/$', LoginView.as_view(), {'authentication_form': 
        LoginForm}, name='login'),
    url(r'^logout/$', LogoutView.as_view(), name='logout'),
    url(r'^password-change/$', PasswordChangeView.as_view(), 
        name='password_change'),
    url(r'^password-change/done/$', PasswordChangeDoneView.as_view(), 
        name='password_change_done'),
    url(r'^password-reset/$', PasswordResetView.as_view(), 
        name='password_reset'),
    url(r'^password-reset/done/$', PasswordResetDoneView.as_view(), 
        name='password_reset_done'),
    url(r'^password-reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-
        Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        PasswordResetConfirmView.as_view(), 
        name='password_reset_confirm'),
    url(r'^password-reset/complete/$', 
        PasswordResetCompleteView.as_view(), 
        name='password_reset_complete')
]

forms.py

from django.contrib.auth.forms import AuthenticationForm
from django.forms import CharField, TextInput, PasswordInput


class LoginForm(AuthenticationForm):
    username = CharField(widget=TextInput(attrs={'class': 'form-
    control'}))
password = CharField(widget=PasswordInput(attrs={'class': 'form-
    control'}))

views.py

@login_required(
    redirect_field_name=reverse_lazy('login'),
    login_url=reverse_lazy('login'))
def dashboard(request):
    return render(request, 'account/dashboard.html', {'section': 
        'dashboard'})

login form

回答1:

In my templates I use Widget Tweaks

<form method='POST' action="/" enctype='multipart/form-data'>
 {% load widget_tweaks %}
 {% csrf_token %}
 {{ form.first_name |add_class:"customCSS1 customCSS2" }}
 {{ form.second_name |add_class:"form-control customCSS4" }}
</form>
{{ form.media.js }}

with this plugin you can style the form as you wish. You could add your form-control class or use a personal CSS class like

.customCSS1{
  width60%;
  border-radius:5px;
 }