GreenGodot
GreenGodot

Reputation: 6753

Writing a Django ChoiceField that refreshes a page

I'm adding functionality to a Django project where a drop down list is used. When a choice on the list is selected, the page it is on reloads. The difference being the value of the drop down choice selected is then passed onto a method on page reload, otherwise render page as normal.

I believe I have the code side of the functionality done correctly but when I select a drop down choice, nothing happens! I'm new to Django development (specifically the HTML side) so any help would be appreciated. Here is my code:

def view(request): 

if request.method == "POST":

    form = ChoiceForm(request.POST)
    if form.is_valid():

        form.save()
        value = form.cleaned_data['content']
        value = dict(form.fields['content'].choices)[value]
        print (value)

else:

    form = ChoiceForm()
    print("Printing default")
    value = "1";

...
data = method(val = value)
....

pageModel = {
             "page":page,
             "form": form,
            'table': table, 
             }

return render(request, 'url/example.html', pageModel)    
....    class ChoiceForm(forms.Form):

CHOICES = (
   (1, "Adwords"),
   (2, "Bing"), 
   (3, "Combined"), content = forms.ChoiceField(choices=CHOICES, required=False)

And my HTML block referring to the form:

<form action='url/where/view/is/located' method='post'>{% csrf_token %}
    {{ form.as_p }}
</form>

Upvotes: 0

Views: 852

Answers (2)

starylass
starylass

Reputation: 31

This is what I have:

from django.shortcuts import render, get_object_or_404, redirect
from .models import *
from .forms import *
from simple_history.models import HistoricalRecords
from datetime import date


def wypozycz_tester(request, numer_seryjny):
    item = get_object_or_404(Tester, numer_seryjny=numer_seryjny)
    numer = item.numer_seryjny
    if request.method == "POST":
        form = testerForm(request.POST, instance = item, initial={'data_wypozyczenia': date.today()}))
        item.wypozyczony = True
        form.save()
        return redirect('display_testery')

    else:
        form = testerForm(instance=item)
        return render(request, 'wypozycz.html', {'form':form, 'numer':numer})

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599610

You can't do this as described without Javascript.

Simply selecting something from a dropdown doesn't by itself trigger a submit; normally, you'd also need a submit button, but if you want to do it automatically you'd need some JS code that listens to the onchange event of the select element and submits the form.

Upvotes: 2

Related Questions