I am trying to set the field to a certain value after the form is initialized.
我试图在表单初始化后将字段设置为一个特定的值。
For example, I have the following class.
例如,我有下面的课程。
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))
6 个解决方案
#1
107
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.
由于您没有传递POST数据,所以我假设您要做的是设置一个初始值,该值将显示在表单中。这样做的方法是使用初始关键字。
form = CustomForm(initial={'Email': GetEmailString()})
See the Django Form docs for more explanation.
有关更多的解释,请参阅Django表单文档。
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()
Check the referenced docs above for more on using cleaned_data
查看上面引用的文档,了解更多关于使用cleaned_data的信息
#2
77
If you've already initialized the form, you can use the initial property of the field. For example,
如果已经初始化表单,可以使用字段的初始属性。例如,
form = CustomForm()
form.fields["Email"].initial = GetEmailString()
#3
6
Something like Nigel Cohen's would work if you were adding data to a copy of the collected set of form data:
如果你将数据添加到收集到的表单数据集的副本中,那么类似奈杰尔•科恩(Nigel Cohen)的东西就会起作用:
form = FormType(request.POST)
if request.method == "POST":
formcopy = form(request.POST.copy())
formcopy.data['Email'] = GetEmailString()
#4
6
If you want to do it within the form's __init__
method for some reason, you can manipulate the initial
dict:
如果您出于某种原因想要在表单的__init__方法中进行此操作,您可以操作初始的敕令:
class MyForm(forms.Form):
my_field = forms.CharField(max_length=255)
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.initial['my_field'] = 'Initial value'
#5
1
Just change your Form.data field:
只是改变形式。数据字段:
class ChooseProjectForm(forms.Form):
project = forms.ModelChoiceField(queryset=project_qs)
my_projects = forms.BooleanField()
def __init__(self, *args, **kwargs):
super(ChooseProjectForm, self).__init__(*args, **kwargs)
self.data = self.data.copy() # IMPORTANT, self.data is immutable
# any condition:
if self.data.get('my_projects'):
my_projects = self.fields['project'].queryset.filter(my=True)
self.fields['project'].queryset = my_projects
self.fields['project'].initial = my_projects.first().pk
self.fields['project'].empty_label = None # disable "-----"
self.data.update(project=my_projects.first().pk) # Update Form data
self.fields['project'].widget = forms.HiddenInput() # Hide if you want
#6
-12
Another way to do this, if you have already initialised a form (with or without data), and you need to add further data before displaying it:
另一种方法是,如果您已经初始化了一个表单(有或没有数据),并且需要在显示它之前添加更多的数据:
form.data['Email] = GetEmailString()
#1
107
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.
由于您没有传递POST数据,所以我假设您要做的是设置一个初始值,该值将显示在表单中。这样做的方法是使用初始关键字。
form = CustomForm(initial={'Email': GetEmailString()})
See the Django Form docs for more explanation.
有关更多的解释,请参阅Django表单文档。
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()
Check the referenced docs above for more on using cleaned_data
查看上面引用的文档,了解更多关于使用cleaned_data的信息
#2
77
If you've already initialized the form, you can use the initial property of the field. For example,
如果已经初始化表单,可以使用字段的初始属性。例如,
form = CustomForm()
form.fields["Email"].initial = GetEmailString()
#3
6
Something like Nigel Cohen's would work if you were adding data to a copy of the collected set of form data:
如果你将数据添加到收集到的表单数据集的副本中,那么类似奈杰尔•科恩(Nigel Cohen)的东西就会起作用:
form = FormType(request.POST)
if request.method == "POST":
formcopy = form(request.POST.copy())
formcopy.data['Email'] = GetEmailString()
#4
6
If you want to do it within the form's __init__
method for some reason, you can manipulate the initial
dict:
如果您出于某种原因想要在表单的__init__方法中进行此操作,您可以操作初始的敕令:
class MyForm(forms.Form):
my_field = forms.CharField(max_length=255)
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.initial['my_field'] = 'Initial value'
#5
1
Just change your Form.data field:
只是改变形式。数据字段:
class ChooseProjectForm(forms.Form):
project = forms.ModelChoiceField(queryset=project_qs)
my_projects = forms.BooleanField()
def __init__(self, *args, **kwargs):
super(ChooseProjectForm, self).__init__(*args, **kwargs)
self.data = self.data.copy() # IMPORTANT, self.data is immutable
# any condition:
if self.data.get('my_projects'):
my_projects = self.fields['project'].queryset.filter(my=True)
self.fields['project'].queryset = my_projects
self.fields['project'].initial = my_projects.first().pk
self.fields['project'].empty_label = None # disable "-----"
self.data.update(project=my_projects.first().pk) # Update Form data
self.fields['project'].widget = forms.HiddenInput() # Hide if you want
#6
-12
Another way to do this, if you have already initialised a form (with or without data), and you need to add further data before displaying it:
另一种方法是,如果您已经初始化了一个表单(有或没有数据),并且需要在显示它之前添加更多的数据:
form.data['Email] = GetEmailString()