abautista
abautista

Reputation: 2780

How to display the data contained in Django models in a Django Dropdown menu form?

Currently, I have some data stored in a Django model with the following structure:

#Django model
from django.db import models

class Customer(models.Model):
    first_name = models.Charfield(max_length = 120, null = False, blank = False)
    last_name = models.Charfield(max_length = 120, null = False, blank = False)

    def __str__(self):
        return self.first_name+ " " + self.last_name

I want to display all the customers that are stored in the Customer model in the DropDown menu form. What I tried was the following but I've got no success:

#Django form
from .models import Customer

# This throws as a result <Django.db.models.query.utils.deferred.attribute at 0x00013F> inside of the DropDown Menu form
class DropDownMenuCustomer(forms.Form):
    Customer = forms.ChoiceField(choices=[(x,x) for x in str(Customer.first_name)+str(" ")+ str(Customer.last_name))])

Another possibility without success was:

#Django form
from .models import Customer

class DropDownMenuCustomer(forms.Form):
    querySet = Customer.objects.all()
    list_of_customers = []
    for customer in querySet:
        list_of_customers.append(customer.first_name + " " + customer.last_name)

    customer= forms.ChoiceField(choices=[(x) for x in list_of_customers)])

This last possibility does not find list_of_customers, just as if the variable has not been declared. How can I display the data stored in the Django models in the Django forms?

Upvotes: 1

Views: 88

Answers (2)

Jonathan
Jonathan

Reputation: 8890

You'll have to write it differently. To get all the customer names you'll have to define it in its own function. That way you can generate the choices that way.

def customer_names():
    list_of_customers = []
    querySet = Customer.objects.all()
    for customer in querySet:
        list_of_customers.append(customer.first_name + " " + customer.last_name)
    return list_of_customers


class DropDownMenuCustomer(forms.Form):

    customer= forms.ChoiceField(choices=[(x) for x in customer_names())])

Upvotes: 3

Mauricio Cortazar
Mauricio Cortazar

Reputation: 4213

you can use forms.ModelChoiceField is much more better like:

customer = forms.ModelChoiceField(queryset=Customer.objects.all(), empty_label="(Nothing)")

More information

Upvotes: 1

Related Questions