adhg
adhg

Reputation: 10863

Django dropdown [onChange] box with selected values but can't get the selected value

I have a dropdown selection of titles that upon selection of specific title, an action (should) run.

What I have:

form.py

class CronForm(forms.Form): 
    title = forms.ModelChoiceField(queryset=GlobalFID.objects.all().order_by('-title_date'), widget=forms.Select(attrs={"onChange":'change_title()'}))

view.py [title_change_view ]

my_form = CronForm() #initial=data
return render(request, 'research/title_result.html',{"my_form":my_form})

html

    <form method="post" >
        {% csrf_token %}
        {{ my_form }}
    </form>

and on the js side:

function change_title()
{ 
    var murl= "{% url 'title_change_view' %}"; 
    window.location = murl; 
}

my goal is to have the SELECTED title from {{my_form}} in the view title_change_view. While the redirection works, I can't get the selected value.

Strategies I considered/tried:

  1. In the title_change_view I added if request.method == 'POST': but it's not a post (so it overlook it) so I can't read the form.

  2. var murl= "{% url 'title_change_view' %}"; to add additional parameter ?title=[SELCTED_VALUE] but couldn't figure out how to add the SELECTED title into murl or into the change_title() fuction.

any idea?

Upvotes: 0

Views: 1875

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

This isn't the right approach at all. Redirecting the browser will never submit any data. You need to actually post it; in your case, you can do it by simply submitting the form.

<form id="my_form" method="post" action="{% url 'title_change_view' %}">
    {% csrf_token %}
    {{ my_form }}
</form>

...

function change_title() { 
    document.getElementById('my_form').submit();
}

Upvotes: 1

Related Questions