[Django]-Use data from GET request in get_intial() and get_form_kwargs() of FormVIew

6👍

First of all, bookmark this.

Second, get_initial() and get_context_data() solve 2 different problems:

  • get_initial is to pass initial values to a form.
  • get_context_data is to pass variables to a template

As you can see in above site, the form is injected into the template variables through get_context_data() and that’s where your recursion problem comes from:

- get()
 |- get_context_data()     <----------------------------------\
   |- get_form()                                              |
     |- get_form_kwargs()                                     |
       |- get_initial() --> you call get_context_data here ---/

Now, how your GET parameters and form should be working together is unclear from your question, but if you need some values from GET for initial form values, then get them inside get_initial().

UPDATE:

  1. I’d not have a method get_queryset() with a signature like this, reason is that several views dealing with models also have a get_queryset() method with a different signature. get_trips() in this context makes a lot of sense
  2. You’ve already extracted a few functionalities, which is good, but the "finding closest to searched date" can be extracted as well and it’s result stored on self.
  3. It’s possible to use __range lookups which probably makes your logic easier. Change the semantics to "find trips between 30 days before and 30 days after search date". This is not the same but a good enough approach in practical terms.

If you’re still stuck, let us know on what specifically.

Leave a comment