Search code examples
pythonhtmldjangoformspgadmin-4

How to implement a dropdown populated with values from a database


I am very new to Python and Django, thus having this issue. What I want to do is create a behavior of HTML Select tag with a Django form. This dropdown/select has to be populated with values from a database.

What I already have is location = forms.ModelChoiceField(queryset = MyModel.objects.all()) which does give me a select/drowpdown control, but I need it to display one value from the database and have a different one as an actual value (both from the same table just different columns)

What I mean in HTML code would look like this:

<select>
  <option value="1">Berlin</option>
  <option value="2">New York</option>
  <option value="3">London</option>
  <option value="4">Riga</option>
</select> 

So, using the form I would see a name of the city, eg. London, but when it is selected and submit is called I insert 3 in the database.

Looking forward to your suggestions.

EDIT:

class Event(models.Model):
    eventid = models.AutoField(primary_key=True)
    date = models.DateField(blank=True, null=True)
    time = models.TimeField(blank=True, null=True)
    description = models.CharField(max_length=2000, blank=True, null=True)
    price = models.IntegerField(blank=True, null=True)
    locationid = models.ForeignKey(Location, models.DO_NOTHING, db_column='locationid', blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'event'

class Location(models.Model):
    locationid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=256, blank=True, null=True)
    capacity = models.IntegerField(blank=True, null=True)
    type = models.CharField(max_length=256, blank=True, null=True)
    cityid = models.ForeignKey(City, models.DO_NOTHING, db_column='cityid', blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'location'

So I have an id reference to another table from which I want to get the name of location and populate the select/dropdown with those names. When the user does a select it shouldn't take the name, but an integer/id. Does that make sense?


Solution

  • You can try this

    in forms.py

    class your_form(forms.ModelForm):
    
        def __init__(self, *args, **kwargs):
            super(your_form, self).__init__(*args, **kwargs)
            self.fields['location'].label_from_instance = self.label_from_instance
    
        @staticmethod
        def label_from_instance(obj):
            return "Label %s" % obj.name
    

    or from docs

    from django.forms import ModelChoiceField
    
    class MyModelChoiceField(ModelChoiceField):
        def label_from_instance(self, obj):
            return "My Object #%i" % obj.id
    

    refer this