[Fixed]-Processing a Django form when there are multiple possibilities?

1👍

✅

There is no “right way” to handle this, but one thing you could do to consolidate is use a mapping.

Example:

form_mappings = {
    'US': USLocationForm,
    'GB': GBLocationForm,
    #...
}

def enter_location(request):
    country = request.session['country']
    country_form = form_mappings.get(country, OtherLocationForm)

    if request.method == "POST":
        form = country_form(request.POST)
        #...
    else:
        form = country_form(initial={'country': country})

This way, you can extend the code for further countries, and not have to change the code at all..

Leave a comment