170๐
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()})
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()
Check the referenced docs above for more on using cleaned_data
106๐
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()
- [Django]-Django: why i can't get the tracebacks (in case of error) when i run LiveServerTestCase tests?
- [Django]-Redirect to named url pattern directly from urls.py in django?
- [Django]-The QuerySet value for an exact lookup must be limited to one result using slicing. Filter error
19๐
If you want to do it within the formโs __init__
method for some reason, you can manipulate the initial
dict:
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'
- [Django]-Redirect to Next after login in Django
- [Django]-Django โ How to rename a model field using South?
- [Django]-How to filter empty or NULL names in a QuerySet?
13๐
Something like Nigel Cohenโs would work if you were adding data to a copy of the collected set of form data:
form = FormType(request.POST)
if request.method == "POST":
formcopy = form(request.POST.copy())
formcopy.data['Email'] = GetEmailString()
- [Django]-How can I keep test data after Django tests complete?
- [Django]-Best practices for getting the most testing coverage with Django/Python?
- [Django]-Timestamp fields in django
10๐
If you have initialized the form like this
form = CustomForm()
then the correct way as of Jan 2019, is to use .initial
to replace the data. This will replace the data in the intial
dict that goes along with the form. It also works if you have initialized using some instance such as form = CustomForm(instance=instance)
To replace data in the form, you need to
form.initial['Email'] = GetEmailString()
Generalizing this it would be,
form.initial['field_name'] = new_value
- [Django]-Best practice for Django project working directory structure
- [Django]-How to access the local Django webserver from outside world
- [Django]-Retrieving parameters from a URL
6๐
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
- [Django]-Django logging of custom management commands
- [Django]-How do I create a slug in Django?
- [Django]-How to monkey patch Django?
2๐
To throw yet another way into the mix: this works too, with a bit more modern notation. It just works around the fact that a QueryDict
is immutable.
>>> the_form.data = {**f.data.dict(), 'some_field': 47}
>>> the_form['some_field'].as_widget()
'<input type="hidden" name="some_field" value="47"
class="field-some_field" id="id_some_field">'
- [Django]-What's the idiomatic Python equivalent to Django's 'regroup' template tag?
- [Django]-How can I temporarily disable a foreign key constraint in MySQL?
- [Django]-Django project models.py versus app models.py
1๐
in widget use โvalueโ attr.
Example:
username = forms.CharField(
required=False,
widget=forms.TextInput(attrs={'readonly': True, 'value': 'CONSTANT_VALUE'}),
)
- [Django]-Get count of related model efficiently in Django
- [Django]-Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
- [Django]-Django 2.0 โ Not a valid view function or pattern name (Customizing Auth views)
0๐
In your case it seems that you are trying to create a new empty (unbound) form and set an initial value that will be displayed in this form.
In this case it is better to instantiate the form with the initial value (instead of trying to change the value after the form is initialized).
There are multiple options how to do this but the simplest one would be the one presented in Grantโs answer. i.e.:
form = CustomForm(initial={'Email': GetEmailString()})
- [Django]-Django 1.3.1 compilemessages. Error: sh: msgfmt: command not found
- [Django]-When to use Serializer's create() and ModelViewset's perform_create()
- [Django]-What is the most efficient way to store a list in the Django models?
-11๐
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 = Form(request.POST.form)
form.data['Email'] = GetEmailString()
- [Django]-Django: Arbitrary number of unnamed urls.py parameters
- [Django]-How do I clone a Django model instance object and save it to the database?
- [Django]-Paginating the results of a Django forms POST request