1

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?

2 Answers 2

3

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())])
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

More information

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.