How to get select field text from html form in django?

Question:

I have created a form with select field in template ehrinfo.html

<form action="{% url 'ehrs:compcreate' %}" method="GET">
    <select>
        <option value="Vital Signs">Vital Signs</option>
        <option value="Cancer Signs">Cancer Signs</option>
    </select><br><br>
    <input type="submit" value="Select Template" class="addehr">
</form>

I have defined form class as:

class templateselect(forms.Form):
CHOICES = (
    ('Vital Signs', 'Vital Signs'),
    ('Cancer Signs', 'Cancer Signs'),
)
template = forms.ChoiceField(widget=forms.Select, choices=CHOICES)

Now I want to get selected text from this form in view compcreate. So I used:

def compcreate(request):
if request.method == 'GET':
    form = templateselect(request.GET)
    print("a")
    if form.is_valid():
        print("b")
        template = str(form.cleaned_data["template"])

but it cant get past the if form.is_valid(): part as ‘a’ is printed but ‘b’ is not printed on console. What is the problem? How can I get the selected text in compcreate()?

Asked By: Tarun Khare

||

Answers:

The proper way to render your form would be to pass it in to your template via the context object and change your template. For example:

<form action="{% url 'ehrs:compcreate' %}" method="GET">
    {{ form.as_p }}<br><br>
    <input type="submit" value="Select Template" class="addehr">
</form>

If you want to stick with your current setup, looking at the html produced by the previous solution suggests that adding a name (equal to the name of your field in the Form class declaration) to your select field should also work:

<form action="{% url 'ehrs:compcreate' %}" method="GET">
<select name="template">
    <option value="Vital Signs">Vital Signs</option>
    <option value="Cancer Signs">Cancer Signs</option>
</select><br><br>
<input type="submit" value="Select Template" class="addehr">

Answered By: tanboon

This approach works with ModelForm and POST request:

def compcreate(request):
    if request.method == 'POST':
        form = templateselect(request.POST)
        if form.is_valid():
            ts = form.save(commit=False)
            print(ts.template)

Let me know if it works in your case.

Answered By: Jan Lněnička
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.