vhd
vhd

Reputation: 2078

Passing the value of selected option of dropdown value to django database

I am working on a Django project. I am making an HTML form (not using the Django forms). Now, I can pass the values of "text" inputs to the database using the "POST" method (just by giving the name to the input tag, and by accessing them from views.py). But I have a problem doing the same when it comes to the response of a dropdown menu. I have a dropdown menu, from which, a user can select multiple options. Now, how do I detect the options selected by the user and pass them to views.py so that I can add them into the database from there?

Here is the code of the dropdown menu.

Enter City (hold Ctrl to select more than one)
<label for="inputCity" class="sr-only">Select City to be shipped to</label><br>
<select multiple class="form-control" id="optCity" name="city" required>
    {% for city in all_cities %}
        <option>{{city.city_name}}</option>
    {% endfor %}
</select><br>

Upvotes: 4

Views: 14929

Answers (2)

madzohan
madzohan

Reputation: 11808

<option value="{{ city.id }}">{{city.city_name}}</option>

http://www.w3schools.com/tags/tag_option.asp


EDIT

form (template)

<form action="/" method="post"> {% csrf_token %}
        <p>Enter City (hold Ctrl to select more than one)</p>
        <label for="optCity" class="sr-only">Select City to be shipped to</label><br>
        <select multiple class="form-control" id="optCity" name="city" required>
            {% for city in all_cities %}
                <option value="{{city.id}}">{{city.name}}</option>
            {% endfor %}
        </select>
        <p><input type="submit" value="Send form"/></p>

    </form>

view

def form_view(request):
    context = {
        'all_cities': City.objects.all()
    }

    if request.POST:
        city_pk_list = request.POST.getlist('city', None)
        print(request.POST.getlist('city', None))

        selected_city_obj_list = City.objects.filter(pk__in=city_pk_list)
        print(selected_city_obj_list)


    return render(request, 'index.html', context=context)

model

class City(models.Model):
    name = models.CharField(max_length=512)

    def __unicode__(self):
        return self.name

Assume it renders

<option value="1">Kyiv</option>

<option value="2">Lviv</option>

<option value="3">Odessa</option>

<option value="4">New York</option>

<option value="5">Tbilisi</option>

And I've selected Kyiv and Odessa

So in output will be

[u'1', u'3']
[<City: Kyiv>, <City: Odessa>]

Upvotes: 1

Sylvain Biehler
Sylvain Biehler

Reputation: 1433

As the question is open, you have many options. Here are 2 very simple solutions

The simpliest, use aChoiceFiled. Documentation is here.

If you need more control, you can use a specific widget. See the documentation here

Upvotes: 0

Related Questions