How to have a CreateView that looks up information via HTMX and updates the form dynamically?

I'm a python and Django newbie. Also a newbie in StackOverflow... I'm trying to build a CreateView with a form that contains a button to lookup information via a GET request using HTMX. A user would encounter the form completely blank at first. Once they input a specific field (in this case a serial number), they can click the button that initiates the lookup/GET request. After the information is retrieved via the GET, I would like to update specific fields in the form with some of the information from the GET (essentially like an auto-complete). So far I have been able to build the initial CreateView (which is straightforward) and have been able to setup the button that does the HTMX GET request; I have also been able to retrieve the information needed but where I'm stuck is on being able to update/inject the values retrieved into specific fields from the form after the GET request. What are the steps I should take to handle that specific part? I have tried adding the form into the view that manages the HTMX get request and assigning some of the "initial" values, later having the form with the values defined as "initial" and passing the form to the HttpResponse but it's not working as intended. Example below:

class LookupView(View):
    def get(self, request, *args, **kwargs):
         if request.htmx:
            form = AddItemForm()
            #GET request actions go here that fetch info that is assigned to variables to be used in form
            data = {'field1': field1value,'field2': field2value}
            form = AddItemForm(initial=data)
        return HttpResponse(form)
    else:
        return HttpResponse('No value provided')

Thank you for all the help and guidance in advance!

The common approach is to simply return the options as an html snippet (which htmx expects). So, you may have a partial like
partials/select.html:

{% for option in options %}  
\<option value="{{option.value}}"\>{{option.label}}\</option\>  
{% endfor %}

Then your LookupView can return it with the options filtered based on the parameters you are getting.

LookupView(View):  
def get(self, request, \*args, \*\*kwargs) ...  
options = your_filtered_values here # maybe a queryset from the database?  
response = render(request," partials/select.html", dict(options=options))  
\# set response headers to control where and how to place the returned template  
response\["Hx-Retarget"\] = "css_selector_of_the_target"  
response\["Hx-Reswap"\] = "innerHTML"  
return response
Back to Top