Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a value to Django Form's init method from a view?

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
like image 538
Jayan Karthik Pari Avatar asked Jan 28 '15 23:01

Jayan Karthik Pari


People also ask

How to initialize form in Django?

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/.

What is form as_ p in Django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.

What method can you use to check if form data has changed when using a form instance?

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.

How do forms work in Django?

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 ...


1 Answers

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
like image 101
meshy Avatar answered Sep 23 '22 17:09

meshy