forms.py
class AddDuration(forms.Form):
def __init__(self, *args, **kwargs):
super(AddDuration, self).__init__(*args, **kwargs)
// set value to relates_to_choices
relates_to_choices = ????????????? // Something like self.choices
self.fields['duration'].choices = relates_to_choices
duration = forms.ChoiceField(required=True)
Now, I have a views.py file that has a class
class AddDurationView(FormView):
template_name = 'physician/add_duration.html'
form_class = AddDurationForm
Method 1 – Adding initial form data in views.py This first and most commonly used method to add initial data through a dictionary is in view.py during the initialization of a form. Here is the code of views.py with some added data. Now open http://127.0.0.1:8000/.
{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.
Use the has_changed() method on your Form when you need to check if the form data has been changed from the initial data. has_changed() will be True if the data from request.
Django's form handling uses all of the same techniques that we learned about in previous tutorials (for displaying information about our models): the view gets a request, performs any actions required including reading data from the models, then generates and returns an HTML page (from a template, into which we pass a ...
Override the get_form_kwargs()
method on the view.
views.py
class AddDurationView(FormView):
template_name = 'physician/add_duration.html'
form_class = AddDurationForm
def get_form_kwargs(self):
kwargs = super(AddDurationView, self).get_form_kwargs()
kwargs['duration_choices'] = (
('key1', 'display value 1'),
('key2', 'display value 2'),
)
return kwargs
forms.py
class AddDurationForm(forms.Form):
duration = forms.ChoiceField(required=True)
def __init__(self, duration_choices, *args, **kwargs):
super(AddDurationForm, self).__init__(*args, **kwargs)
// set value to duration_choices
self.fields['duration'].choices = duration_choices
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With