5👍
Finally, I figured it out by myself.
To solve this problem, the context_data in the original template based solution should be passed as initial
into the constructor of forms.Form
.
For example, with django CVB, get_initial
is the right point to pass initial data to forms
def get_initial(self):
initial = Super(ThisCBV, self).get_initial()
redirect_field_name = self.get_redirect_field_name()
if (redirect_field_name in self.request.GET and
redirect_field_value in self.request.GET):
initial.update({
"redirect_field_name": redirect_field_name,
"redirect_field_value": self.request.REQUEST.get(
redirect_field_name),
})
return initial
Then, it is possible to add a field dynamically in the instance of forms.Form
def __init__(self, *args, **kwargs):
super(ThisForm, self).__init__(*args, **kwargs)
if ('redirect_field_name' in kwargs['initial'] and
'redirect_field_value' in kwargs['initial']):
self.has_redirection = True
self.redirect_field_name = kwargs['initial'].get('redirect_field_name')
self.redirect_field_value = kwargs['initial'].get('redirect_field_value')
## dynamically add a field into form
hidden_field = forms.CharField(widget=forms.HiddenInput())
self.fields.update({
self.redirect_field_name: hidden_field
})
## show this field in layout
self.helper = FormHelper()
self.helper.layout = Layout(
Field(
self.redirect_field_name,
type='hidden',
value=self.redirect_field_value
)
)
1👍
You can ask Django Crispy Form to not render the <form>
tag, and only generate the <input>
tags, which will let you then add your own extra <input>
.
You do this by setting the form helper’s form_tag
property to False
.
This is all documented in detail here. Note that unlike the example, you won’t need {% crispy second_form %}
, you’ll only need to add your own if
block there.
- [Django]-How can I use Flex to access foreign-keyed fields in Django?
- [Django]-AttributeError: 'CombinedExpression' object has no attribute 'default_alias'
- [Django]-Do I need to start a worker?
- [Django]-Django multiple forms with formsets
- [Django]-The view ats.views.index didn't return an HttpResponse object. It returned None instead
Source:stackexchange.com