使用django表单模板

时间:2015-03-30 11:40:19

标签: python django templates

我正在尝试使用模板(简单的模板)来重置密码,使用Django Forms和Templates。以下是使用的文件:

forms.py

from django import forms
from django.contrib.auth import get_user_model

User = get_user_model()


class ResetPasswordForm(forms.Form):
    new_password = forms.CharField(
        label='New password',
        widget=forms.PasswordInput(render_value=False),
    )
    confirm_new_password = forms.CharField(
        label='Confirm New password',
        widget=forms.PasswordInput(render_value=False),
    )

class Meta:
    model = User
    fields = ('password')

def clean(self):
    password = self.cleaned_data['new_password']
    confirm_password = self.cleaned_data['confirm_new_password']
    if password != confirm_password:
        raise forms.ValidationError(u'Passwords are not equal')
    return self.cleaned_data

reset_password.html

<html>
    <head>
        <title>Reset Password</title>
    </head>
    <body>
        <form id="reset_password_form" method="post">
            {% csrf_token %}
            {{ reset_password_form.as_p }}
            <input type="submit" name="submit" value="Reset Password" />
        </form>
    </body>
</html>

views.py我正在通过

调用此页面
return render(request, "reset_password.html",
              {'form': reset_password_form})

并且输出仅显示Reset Password的按钮,其他两个密码字段未显示。有人可以指出任何错误或任何方式吗?

1 个答案:

答案 0 :(得分:3)

您正在变量reset_password_form中传递form。因此要在模板上进行渲染

更改

{{ reset_password_form.as_p }}

{{ form.as_p}}

{'form': reset_password_form}更改为{'reset_password_form': reset_password_form}