表单初始化后,Django设置字段值 [英] Django set field value after a form is initialized

查看:96
本文介绍了表单初始化后,Django设置字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

初始化表格后,我试图将字段设置为某个值。

I am trying to set the field to a certain value after the form is initialized.

例如,我有以下课程。

class CustomForm(forms.Form):
    Email = forms.EmailField(min_length=1, max_length=200)

在视图中,我希望能够执行以下操作:

In the view, I want to be able to do something like this:

form = CustomForm()
form["Email"] = GetEmailString()

return HttpResponse(t.render(c))


推荐答案

由于您没有传递POST数据,因此我假设您要尝试设置的初始值将显示在形成。执行此操作的方式是使用 initial 关键字。

Since you're not passing in POST data, I'll assume that what you are trying to do is set an initial value that will be displayed in the form. The way you do this is with the initial keyword.

form = CustomForm(initial={'Email': GetEmailString()})

请参见 Django Form文档以获取更多说明。

See the Django Form docs for more explanation.

如果您在提交表单后尝试更改值,则可以使用以下方式:

If you are trying to change a value after the form was submitted, you can use something like:

if form.is_valid():
    form.cleaned_data['Email'] = GetEmailString()

有关使用 cleaned_data

这篇关于表单初始化后,Django设置字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆