【问题标题】:Styling ModelForms in Django won't work在 Django 中为 ModelForm 设置样式不起作用
【发布时间】: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>

【问题讨论】:

标签: python django twitter-bootstrap python-3.x django-forms


【解决方案1】:

感谢@hansTheFranz 和他的answer 我刚刚使用了这个神奇的工具Widget Tweaks,它运行良好。

我必须使用append_attr 而不是add_class

【讨论】:

  • 当您现在点击接受答案meta.stackexchange.com/questions/5234/… 并接受我的编辑建议时,我很高兴;)
  • 一般来说,当您喜欢答案或至少投赞成票时,请尝试接受答案。由于您现在有 23 分(其他人也对您的答案投了赞成票),当您认为有帮助时,您可以单击向上箭头(例如我对另一个问题的回答,但您不必在那里做我有足够的点:D)。这样,StackOverflow 保持活力,人们互相帮助......
  • 请不要只发布对其他 Stack Overflow 问题的链接答案。相反,投票/标记以关闭为重复,或者,如果问题不是重复的,定制此特定问题的答案。
  • 感谢 hansTheFranz 和 Baum_mit_Augen 帮助我,
猜你喜欢
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 2020-03-20
  • 2017-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多