gmarais
gmarais

Reputation: 1891

Django multiple dropdowns showing model objects

I want to have multiple dropdowns, each showing the available objects from one specific model.

So Dropdown 1:

Apples
Oranges
Pears

and, Dropdown 2:

Apples
Oranges
Pears

etc.

The bonus question is to have these dropdowns linked/be dependent so that as the user selects items, these chosen items are removed from the remaining dropdowns.

Is this possible?

Upvotes: 0

Views: 468

Answers (2)

sheep64
sheep64

Reputation: 94

It is possible. Import your Model to the view-File. Example:

def editUser(request):
    users = "YourModel".objects.all()

    if request.method="POST":
       selected_Item = request.POST['user.id']
       userID = Employee.objects.get(id=selected_item)
       userID.delete()


    context = {
             'user' : users
    }

    return render(request, "your_template_name", context)

So you select your Item by your ID or name. In your Templates you can say "user.your_stuff". So if your Model has things like name you can write user.name. Then delete the stuff.

Context hier is like a Dictonary. You can work with it in your Template.

<form method="POST" > {%csrf_token%}
<select name="user.id">
{% for entry in user %}
    <option>  {{ entry.id }} </option>
{% endfor %}
</select>

<input type = "submit" value="Submit">
</form>

So now you have a DropDown Menu that lists all Entrys from user. You can edit your return in your View so just call the same page and you just "refreshed" the Site and the value you want to delete is away.

Im sorry for my bad english or for my bad explanation. Im still improving my English Skills and im new too StackOverflow and Django too :P If you have any Questions left, im here to help! :)

Upvotes: 1

VicenteC
VicenteC

Reputation: 422

You can use a for loop within a html list.

index.html

<ul >
{% for element in model %} 
<li class="product"> {{ element }} </li>
{% endfor %}
</ul>

views.py

def index_function(request):
    model = product_model_name.objects.all()
    context = {
        'model': model,
    }
    return render(request, 'index.html', context)

Now you only have to style the ul, there are tons of tutorials with different styles!

Bonus question You can handle this problems using JavaScript. Using addEventListener, this and element.style.display = "none" you can hide a linked div changing its css properties.

Upvotes: 1

Related Questions