[Fixed]-Django Dropdown populate from database


If I understood your need correctly, you can do something like:

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

By the way, you should give the name items instead of item, since it’s a collection (but it’s just a remark ;)).

Doing so, you will have a list of all the items in the database.

Then, in the post, here what you need to do:

def selectview(request):
   item  = Item.objects.all() # use filter() when you have sth to filter ;)
   form = request.POST # you seem to misinterpret the use of form from django and POST data. you should take a look at [Django with forms][1]
   # you can remove the preview assignment (form =request.POST)
   if request.method == 'POST':
      selected_item = get_object_or_404(Item, pk=request.POST.get('item_id'))
      # get the user you want (connect for example) in the var "user"
      user.item = selected_item

      # Then, do a redirect for example

   return render_to_response ('select/item.html', {'items':item}, context_instance =  RequestContext(request),)

Of course, don’t forget to include get_object_or_404


Here is a more dry way to do this in 2021:


 from django.db import models

class Country(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

class City(models.Model):
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

class Person(models.Model):
    name = models.CharField(max_length=100)
    birthdate = models.DateField(null=True, blank=True)
    country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True)
    city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return self.name


from django.urls import include, path

from . import views

urlpatterns = [
    path('', views.PersonListView.as_view(), name='person_changelist'),
    path('add/', views.PersonCreateView.as_view(), name='person_add'),
    path('<int:pk>/', views.PersonUpdateView.as_view(), name='person_change'),


from django.views.generic import ListView, CreateView, UpdateView
from django.urls import reverse_lazy
from .models import Person

class PersonListView(ListView):
    model = Person
    context_object_name = 'people'

class PersonCreateView(CreateView):
    model = Person
    fields = ('name', 'birthdate', 'country', 'city')
    success_url = reverse_lazy('person_changelist')

class PersonUpdateView(UpdateView):
    model = Person
    fields = ('name', 'birthdate', 'country', 'city')
    success_url = reverse_lazy('person_changelist')


{% extends 'base.html' %}

{% block content %}
  <h2>Person Form</h2>
  <form method="post" novalidate>
    {% csrf_token %}
      {{ form.as_table }}
    <button type="submit">Save</button>
    <a href="{% url 'person_changelist' %}">Nevermind</a>
{% endblock %}


enter image description here

Reference: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html

Leave a comment