'Django forms select option value hand to same URL

I am having trouble figuring out how get the selected option of a form handed back to the same url as a get context value:

forms.py

class ModeForm(forms.Form):

    MODES = (
        ('','Select a generation mode'),
        ('docker','Docker'),
        ('docker-compose','Docker Compose'),
        ('kubernetes', 'Kubernetes'),
    )

    selectedMode = forms.CharField(label="",
            widget=forms.Select(choices=MODES,
            attrs={
                'class': 'form-control',
                'placeholder': 'Generation mode',
                'onchange': 'form.submit();',
            }),
    )

views.py

# Home page 
def viewHome(request):
    if request.method == 'POST':
        currentMode = request.POST.get('selectedMode')
        form = ModeForm(initial={'name':currentMode})
        print(f"Post Mode is: {currentMode}")

    context = {
        'data': None, 
        'form': form, 
    }
    return render(request, 'main/home.html', context)

I can obtain the selected value on the POST to the view. However, I am not sure how to have that selection remain once the selection has been made and the form is displayed again.

As things are now: The select field has an initial value when the home page is initially loaded. Once a value is selected, the form is posted to the home page. In the request.POST I can get the selected value. However, the select control resets and the value is lost outside of the POST.

What I am attempting to do is, get a selection on form submission. Have that value persist once a value is set.

Is there a recommended way to handle this situation?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source