【发布时间】:2017-07-14 11:11:26
【问题描述】:
我想在 Django 中使用 UserCreationForm,但我需要在其中嵌入 Bootstrap 类,所以我决定重写它,不幸的是它不适用于样式!
这是我的代码
forms.py
class UserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
'password_mismatch': ("The two password fields didn't match."),
}
username = forms.CharField(label=("Password"),
widget=forms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder':'First Name',}))
password1 = forms.CharField(label=("Password"),
widget=forms.PasswordInput(attrs={'class': 'form-control input-lg', 'placeholder':'First Name',}))
password2 = forms.CharField(label=("Password confirmation"),
widget=forms.PasswordInput(attrs={'class': 'form-control input-lg', 'placeholder':'First Name',}),
help_text=("Enter the same password as above, for verification."))
class Meta:
model = User
fields = ("username",)
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
模板.html
<div class="container makemargs"><div class="row"><h3 class="col-sm-offset-3 col-sm-6">Signup</h3></div><div class="row"><div class="col-sm-offset-1 col-sm-2"></div><div class="col-sm-6"><form id="signupForm" action="" method="POST" accept-charset="utf-8" class="form" role="form">{% csrf_token %} {{form}}<button id="submitBtn" class="btn btn-block signup-btn" type="submit" disabled>Create my account</button></form></div></div></div></div>
【问题讨论】:
-
@hansTheFranz 没用! :-) 还是谢谢
-
我的解决方案?有用。我保证:D
-
@hansTheFranz 哇!它真的有效! add_class 没有,但 append_attr 效果很好
标签: python django twitter-bootstrap python-3.x django-forms