I am trying to display a record of a database after a user has selected the record from a dropdown list of one of the fields of the table (in Django). So far I have only seen examples of selecting data from other tables.
I have a model:class Customer(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
customer_number = models.AutoField(primary_key=True)
business_name = models.CharField(max_length=75, null=True, blank=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.CharField(max_length=100, null=True, blank=True)
and a view:
def customer_record(request):
customers = Customer.objects.all()
return render(request, 'customer_record.html', {'customers':customers})
and a form
class Meta:
model = Customer
fields = (‘customer_number’, ‘business_name’, ‘first_name’, ‘last_name’, ’email’)
labels = {‘business_name’:”,
‘first_name’:”,
‘last_name’:”,
’email’:”,}
and the html:
<select class="form-select" aria-label="Default select example">
<option selected>Open this select menu</option>
{% if customers %}
{% for customer in customers %}
<option value={{ customer.last_name }} ></option>
{% endfor %}
{% endif %}
</select>
Trying the above, I get the dropdown that says: “Open the select menu”, and then blank spaces in the dropdown corresponding, I believe, to the number of records I have. I expected to see the last names appear in the dropdown. Once selected, I would like to then display the record.
Coolmike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.