简体   繁体   English

如何在Django UsercreationForm中设置初始值

[英]How to set initial value in Django UsercreationForm

I am beginner in Django and developing a user registration page using the UserCreationForm from django.contrib.auth.forms. 我是Django的新手,正在使用django.contrib.auth.forms中的UserCreationForm开发用户注册页面。 But, unable to set the initial values for password1 and password2 fields. 但是,无法设置password1和password2字段的初始值。

My requirement is when opening the usercreation form the password and re-enter password fields should get filled with an default password. 我的要求是,在打开用户创建表单时,密码和重新输入密码字段应填充为默认密码。

I have tried this way but unable to achieve this requirement. 我已经尝试过这种方法,但无法达到此要求。

views/user.py 意见/ user.py

if request.method == "POST":
    form = UserCreationForm(request.POST)
    if form.is_valid():
        user = form.save()

else:
    form = UserCreationForm(initial={'password1':'testing123','password2':'testing123'})

Any help would be appreciated. 任何帮助,将不胜感激。

It's very bad idea to pre populate with default password. 预填充默认密码是一个非常糟糕的主意。 But however this is general idea about how to achive that. 但是,这是关于如何实现这一目标的一般想法。 And also I recommend to extend the UserCreationForm and do the rest./ 并且我还建议扩展UserCreationForm并完成其余的工作。

# Create form variable...
form = UserCreationForm(initial={
    'password2': 'password',
    'password1': 'password', 
    'username': 'rajasimon'})

# Assign render_value to True
form.fields['password1'].widget.render_value = True
form.fields['password2'].widget.render_value = True

# Return template with form...
return render(request, 'base.html', {'form': form})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM